If there isn't a keyboard input for a set amount of time skip needing input

328 views Asked by At

I am trying to get a keyboard input, but if it doesn't happen in about half a second I want it to continue to the rest of the loop. I tried using kbhit(); but it won't wait for the input, it just loops with out stopping. This is the loop in question:

    while(flags)
{
    gameing.updateDraw(0, 0);
    keyIn = getch();
    //Sleep(20);
    switch(keyIn)
    {
        case UP_ARROW:
                flags = gameing.updateDraw(-1, 1);
                break;
        case DOWN_ARROW:
                flags = gameing.updateDraw(1, 1);
                break;
        case WKEY:
                flags = gameing.updateDraw(-1, 2);
                break;
        case SKEY:
                flags = gameing.updateDraw(1, 2);
                break;
    }

All help will be greatly appreciated. I am trying to avoid using alarm();

2

There are 2 answers

1
Cheers and hth. - Alf On

The comnented call to Sleep indicates that this is a Windows program using <conio.h> functionality, and not a *nix program using curses.

With <conio.h> you can use the kbhit function to check whether there is a keypress.

Place that in a loop that sleeps a little bit between each call.

More advanced you can use the Windows API. Its wait functions can wait on a console handle, with a specified timeout.

The C++ standard library does not have unbuffered keyboard input functionality.

0
jgon On

Try using something like ctime.h or chrono to get the time difference. Then do something like

long lastTime=CurrentTime();
int input=0;
while(!(input=kbhit()) && CurrentTime()-lastTime < 20);
if(input)
    // do stuff with input
// do all the other stuff
lastTime=CurrentTime();

Disclaimer. I'm not particularly familiar with kbhit and things, but based on a little bit of googling, this seems like it ought to work. Also the implementation of CurrentTime is up to you, it doesn't have to be a long or anything, I just chose that for simplicity's sake.