首页 > 解决方案 > C输入getch(),当没有像Snake(游戏)那样按下时跳过

问题描述

我必须在控制台中用 C 语言编写游戏。例如,当我按下空格键时,我想计算一些东西。但只有在我按下键的时候。当我再次松开键时,它应该停止计数,当我再次按下它时会重新开始。我想要它像蛇一样,我的意思是当用户按下它时它不会停止输入它获取输入。

我已经尝试过使用 kbhit,它会计数,当我按下某个东西时,它永远不会打印任何内容,即使我再次按下一个键。

while (1) {
        h = kbhit();
        fflush(stdin);
        if (h) {

            printf("%d\n", a);
            a += 1;

        } else {
            printf("nothing\n");
        }

    }

我期望什么都没有 没有 没有 presses a key 0 没有 presses key again 1 hold on key 2 3 4

谢谢

标签: cinputheaderdev-c++

解决方案


从您的代码中,您没有将按下的键存储到变量中。请试试这个方法。

前 3 行显示了如何将键盘点击变量存储到 h 中。其余的将增加 a 值。

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

推荐阅读