c++kbhit

Using multiple _kbhit() in a loop


I have a Spaceship object that has 2 methods. First method is move()

char touche;

if(_kbhit() != 0)
{
    touche = _getch();
    if(touche == 'k' || touche == 'l')
    {
        modifyPosition(touche);
    }
}

Second method is shoot()

char touche;

if(_kbhit() != 0)
{
    touche = _getch();
    if(touche == char(32))
    {
        if(nbLasers < 30)
        {
            addLaser();
            compteur++;
        }
    }
}

Both methods are called in a while, one after the other, so the second method almost never works, because I would need to be pressing "Space" exactly after it has went through the move() method. I want to keep the 2 methods seperated, is there a way to make this work?


Solution

  • One simple approach would be to make a new method read_keyboard().

    That function should store the keyboard state, and your other methods can just read that stored state.

    if(_kbhit() != 0)
    {
        // I'm only explicitly writing "this->" to show that it's a member variable.
        this->touche = _getch();
    }
    else
    {
        this->touche = 0;
    }
    

    For example, move now simply becomes:

    if(touche == 'k' || touche == 'l')
    {
        modifyPosition(touche);
    }