在循环中使用多个_kbhit()

Using multiple _kbhit() in a loop

本文关键字:kbhit 循环      更新时间:2023-10-16

我有一个太空船对象,它有两个方法。第一个方法是move()

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

第二个方法是shoot()

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

两个方法都在一段时间内被调用,一个接一个,所以第二个方法几乎不工作,因为我需要在它经过move()方法后恰好按下"Space"。我想保持两种方法分开,有办法让这个工作吗?

一个简单的方法是创建一个新方法read_keyboard()

该函数应该存储键盘状态,而您的其他方法可以读取该存储状态。

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

例如,move现在简单地变成:

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