0

I am a beginner at C++ and trying to code a C++ console based snake game. I was stuck when I cannot move the snake without continuously pressing a key. Now I can do by just pressing the key once but I still do not understand the function of _kbhit() which has helped me do it.

void snake_movement(){
    if(_kbhit())
    switch (getch())
    {
    case 'w':
        y_cordinate--;
        break;
    case 'a':
        x_cordinate--;
        break;
    case 's':
        y_cordinate++;
        break;    
    case 'd':
        x_cordinate++;
        break;
    default:
        break;
    }
}
umer khan
  • 5
  • 4

1 Answers1

1

The _getch() is a blocking function. If no keypresses are available in the input buffer, it will wait for a keypress to become available in the input buffer. So your program gets stuck inside of _getch() until a key is pressed - and that's why it wouldn't "work" unless you keep the key pressed, so that _getch() can keep returning to your program. It still would get "stuck", because new keystrokes are only available at the key repeat rate. That is: in the best case, _getch() may return a few dozen times per second. But only if a key is pressed down, and if the operating system supports autorepeat for that key.

On the other hand, _kbhit() doesn't block. It returns immediately with a zero value if no keypress is available in the input buffer. Otherwise it returns a non-zero value. That indicates that a key is available, and that you can call _getch() to get it. _kbhit() returning non-zero guarantees that _getch() won't block, i.e. it won't wait but will return immediately with the result you need.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313