1

I don't really know how to type the Title so I came up with this. So basically I am trying to make some sort of a snake in C. But I don't know how to make the controls. Lets say you have pressed left arrow and the snake has to move left till another key is pressed but I can't come up with the code for that its always stopping and waiting for me to press the key.

I was thinking for something like this:

for ( i = 0; i < 10 ; i++ ) {
     if( next_move = getch() ) break;
     else Sleep(10);
}
if(!next_move)
    next_move = prev_move;
if( move ( next_move, bite_cord ) ) {
    prev_move = next_move;
    next_move = 0;
    Sleep(300);
    system("CLS");
    printf("You lost. ");
}

My idea was to wait one second and if theres no key pressed to continue with the previous one but if its pressed to save the pressed now.

Do you have any ideas of how to do it?

user007
  • 2,156
  • 2
  • 20
  • 35
Boris Mutafov
  • 297
  • 3
  • 7
  • 3
    Possible duplicate of [C non-blocking keyboard input](http://stackoverflow.com/questions/448944/c-non-blocking-keyboard-input) – Eugene Sh. Jan 25 '16 at 22:11
  • 1
    @EugeneSh. The answer in the duplicate is for UNIX. Seems like OP is asking about DOS. – fuz Jan 25 '16 at 22:22
  • 1
    If it is for Windows, then possible duplicate of http://stackoverflow.com/questions/21294713/non-blocking-i-o-in-c-windows – Derlin Jan 25 '16 at 22:26
  • 4
    Note that in Windows OS the "arrow keys" return *two codes* from `getch`, see [previous answer](http://stackoverflow.com/questions/34451998/how-to-detect-when-the-delete-key-is-pressed-on-the-keyboard/34452407#34452407). Use `kbhit` to detect a keypress before committing to `getch`. – Weather Vane Jan 25 '16 at 22:48

1 Answers1

0

You can use kbhit() The code would be something like

if (kbhit())
    input = getch(); //Or something like that
AKO
  • 172
  • 12