c - 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
谢谢
解决方案
从您的代码中,您没有将按下的键存储到变量中。请试试这个方法。
前 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;
}
}
推荐阅读
- google-bigquery - 如何解决:标量子查询产生了多个元素
- python - 将熊猫数据框加载到 SQL Server 2012
- java - Porterduff 模式(乘法)
- c - C pthread 包括头文件并与 -nolibc 链接
- java - 从 url 下载 .svg 图片
- python - Python中数据框中的计算
- laravel - 在 Laravel 中仅加载某些语言文件(数组)
- javascript - (VUE.js)在组件外部调用时事件不起作用
- firebase - 如何在 Xamarin 表单中保存 Firebase 实时数据库中的 URL?
- java - MainMenu.onCreateOptionsMenu 崩溃