Use of kbhit() with while loop

百般思念 提交于 2019-12-11 02:01:56

问题


Here is the program.

void main( )
{
    int h, v;
    h = 1; v = 10;
    while ( !kbhit( ) || h <= 80 )
    {
        gotoxy( h, v );
        printf( "<--->" );
        delay( 200 );
        clrscr( );
        h = h + 1;
    }
    getch( );
}

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.

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!


回答1:


clrscr() should come before the gotoxy and printf

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'.

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


来源:https://stackoverflow.com/questions/22270310/use-of-kbhit-with-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!