简体   繁体   English

_kbhit() 的 Function

[英]Function of _kbhit()

I am a beginner at C++ and trying to code a C++ console based snake game.我是 C++ 的初学者并尝试编写基于 C++ 控制台的蛇游戏。 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.现在我只需按一次键就可以做到,但我仍然不明白 _kbhit() 的 function 帮助我做到了。

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;
    }
}

The _getch() is a blocking function. _getch()是一个阻塞 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.因此,您的程序会卡在_getch()中,直到按下某个键 - 这就是为什么除非您按住该键,否则它不会“工作”,以便_getch()可以继续返回您的程序。 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.也就是说:在最好的情况下, _getch()可能每秒返回几十次。 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.另一方面, _kbhit()不会阻塞。 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.这表明密钥可用,您可以调用_getch()来获取它。 _kbhit() returning non-zero guarantees that _getch() won't block, ie it won't wait but will return immediately with the result you need. _kbhit()返回非零保证_getch()不会阻塞,即它不会等待但会立即返回您需要的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM