C Input getch(), skip when nothing pressed like Snake (game)

I have to program a game in C in the console. For example I want to count something up when I press the space key. But only while I press the key. When I release the key again it should stop counting and start again when I press it again. I want it like snake, I mean it doesn't stop for the input it gets the input when the user pressed it.

I have tried with kbhit, it counts up and when I press something it prints nothing for ever, even if I press a key again.

while (1) { h = kbhit(); fflush(stdin); if (h) { printf("%d\n", a); a += 1; } else { printf("nothing\n"); } } 

I expect nothing nothing nothing presses a key 0 nothing presses key again 1 hold on key 2 3 4

Thanks

3

2 Answers

From your code, you did not store the key pressed into a variable. Please have a go with this method.

The first 3 lines shows how to store a keyboard hit variable into h. The rest will be incrementing the a value.

while (1) { /* if keyboard hit, get char and store it to h */ if(kbhit()){ h = getch(); } /*** If you would like to control different directions, there are two ways to do this. You can do it with if or switch statement. Both of the examples are written below. ***/ /* --- if statement version --- */ if(h == 0){ printf("%d\n", a); a += 1; } else{ printf("nothing\n"); } /* --- switch statement version --- */ switch(h) { case 0: printf("%d\n", a); a += 1; break; default: printf("nothing\n"); break; } } 

The standard (and correct) way to do this (with <conio.h> stuff) is:

int c; while (1) { 

or:

int c; bool done = false; while (!done) { 

with a loop body something like:

 if (kbhit()) { switch (c = getch()) { case 0: case 0xE0: switch (c = getch()) { /* process "extended" key codes */ } break; /* process "normal" key codes */ case ...: ... } } /* add timer delay here! */ } 

Somewhere in there you should either set delay = true or return from the function, however you wish to set up your loop termination. (I typically recommend you have a function specifically for the loop body.)

You should have access to a function called either "delay" or "sleep" (sleep() is the Windows OS function) that will allow you to delay between loops, somewhere between 50 and 100 milliseconds is more than sufficient.

If you wish to be really sophisticated, you can track the amount of time that has passed since the last loop and delay appropriately. For a game like Snake, however, you can easily skip all that, just use a fixed delay value.


Now, for the question not asked: why are you messing with old <conio.h> stuff anyway? Get yourself a copy of SDL2 and go to town. Life will be easier and the results much more satisfying.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like