结合使用kbhit()和while循环 [英] Use of kbhit() with while loop
问题描述
这是程序.
void main( )
{
int h, v;
h = 1; v = 10;
while ( !kbhit( ) || h <= 80 )
{
gotoxy( h, v );
printf( "<--->" );
delay( 200 );
clrscr( );
h = h + 1;
}
getch( );
}
我正在用C编写一个程序,在其中使用kbhit()
来运行循环,直到按下某个键为止.
因此,箭头"<--->"
将一直向前移动,直到按下某个键或到达屏幕的最后一个像素为止.
I am making a program in C, in which I have used kbhit()
to run a loop until a key is pressed.
so here the arrow "<--->"
will keep on moving forward until a key is pressed or until it reaches the last pixel of the screen.
我想要的是程序每次按'd'
时应将h递增1,而每次按'a'
时应递减1.即h++;
和h--;
并运行另一个循环,直到按下一个字符为止.
这个想法更像是Snake游戏,在该游戏中,蛇一直沿特定方向移动,直到按下键为止.请帮忙!
What I want is that the program should increment h by 1 everytime 'd'
is pressed and decrement by 1 everytime 'a'
is pressed. i.e h++;
and h--;
and run another loop until a character is pressed.
The idea is more like the Snake game, in which the snake keeps on moving in a certain direction until a key is pressed. Help please!
推荐答案
clrscr()应该在gotoxy和printf之前
clrscr() should come before the gotoxy and printf
无论如何,我要做的是创建一个状态变量,只是为了指示蛇应该走的方向,即,如果用户按下"a"或"d",则存储的东西.
Anyway, what I would do is create a state variable, just to indicate the direction the snake should go, i.e., something that stores if the user pressed 'a' or 'd'.
我不会离开循环,只需使用if(kbhit)并获取char.
And I would not leave the loop, just use a if(kbhit) and get the char.
int direction = 1; char control;
while (1)
{
if(kbhit()){
control = getch();
switch (control){
case 'a': direction = -1; break;
case 'd': direction = +1; break;
default: break;
}
}
clrscr( );
gotoxy( h, v );
printf( "<--->" );
delay( 200 );
h = h + direction;
}
这篇关于结合使用kbhit()和while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!