Use of kbhit() with while loop

UmairKhan picture UmairKhan · Mar 8, 2014 · Viewed 7.4k times · Source

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!

Answer

Inox picture Inox · Mar 8, 2014

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