【发布时间】:2018-04-14 16:46:34
【问题描述】:
#include<stdio.h>
#include<Windows.h>
#include<conio.h>
#define Ukey 87
#define ukey 119
#define Dkey 115
#define dkey 83
#define Lkey 97
#define lkey 65
#define Rkey 100
#define rkey 68
int main(){
int x=0;
int y=0;
int prev=rkey;
while(true){
Sleep(50);
system("cls");
printf("x : %d\ny : %d",x,y);
if(!kbhit()){
if(prev==ukey){
y--;
}else if(prev==dkey){
y++;
}else if(prev==lkey){
x--;
}else if(prev==rkey){
x++;
}
}else if(getch()==ukey||getch()==Ukey){
y--;
prev=ukey;
}else if(getch()==dkey||getch()==Dkey){
y++;
prev=dkey;
}else if(getch()==lkey||getch()==Lkey){
x--;
prev=lkey;
}else if(getch()==rkey||getch()==Rkey){
x++;
prev=rkey;
}
}
}
所以基本上我的程序会检测键盘键(我定义为 Ukey、Dkey、Lkey 和 Rkey 的 w、a、s 或 d)。该程序旨在通过按键检测方向,更改 x 和 y 值并保持它直到按下另一个键。
我的问题是,当程序运行并初始化默认方向(右)时,当我按下另一个键时,while 函数就会停止。如果我按下键几秒钟,它只会不断改变 x 和 y 值。
我的代码有什么问题?这是我第一次使用 kbhit,所以您的回答对我来说将是一个巨大的帮助。谢谢。
【问题讨论】:
-
while不是函数,是控制循环。Sleep中的 50 是多少?秒,毫秒?当程序仍在执行Sleep时,您可能正在按下该键。 -
只调用一次 getch()。
-
光标控制和功能键通过
getch返回两个键码。我建议你编写一个像while(1) { while(!kbhit()) ; printf("%d\n", getch()); }这样的小测试程序来检查会发生什么。