【问题标题】:Using `sleep()` for a time delay [duplicate]使用`sleep()`进行时间延迟[重复]
【发布时间】:2014-04-03 12:27:10
【问题描述】:

我试图将程序执行延迟 200 毫秒,然后测试在延迟期间是否按下了某个键。我该怎么做?

我正在尝试使用 C 语言创建一个类似于小鸟的简单电脑游戏。我希望用户有一点点时间(~200 毫秒)来按键让小鸟跳跃,否则它会掉下来,但我在实施延迟时遇到了麻烦。

我在一些论坛 [where?] 上读到 sleep(100) 应该延迟 100 毫秒,但是当我这样做时,我会得到 100 秒。

我也尝试过使用sleep(1/5),但该函数只接受整数。

此外,我需要能够测试在 200 毫秒内是否按下了某个键;我在某处[where?] 读到 kbhit 函数可用于此目的,但我不知道如何使用它。

while(!dead) {
    sleep(200); // what do I put here to get 200ms?

    if (keyWasPressedDuringWait()){ //what do I put here?
        notDeadAnimation():
    }else{
        dead=true;
        deadAimation()
    }
}

【问题讨论】:

标签: c delay sleep flappy-bird-clone


【解决方案1】:

使用usleep() 代替sleep()。前者在微秒内工作。 并使用 _kbhit()+getch() 来发现是否按下了某个键以及是哪个键:

while (!dead) {
    usleep(200*1000); // 200 msec

    if (_kbhit()) { // if key was pressed during sleep
        int key = getch();
        // you can check key value here
        notDeadAnimation();
    } else {
        dead = true;
        deadAnimation();
    }
}

【讨论】:

    【解决方案2】:

    要执行所需的延迟,#include <unistd.h> 并使用 usleep(microseconds)。 (休眠200ms,调用usleep(200000))。

    要测试键盘敲击,#include <conio.h> 并在测试中使用_kbhit()keyboard hit 的缩写) . _kbhit 测试密钥缓冲区中是否有密钥,但不会摆脱它。您还需要使用_getch 检索密钥,将其从密钥缓冲区中删除。我建议在这里定义一个辅助函数:

    int clearKeyBuffer(){
        int count = 0;
        while(_kbhit()){
            _getch();
            count++;
        }
        return count;
    }
    

    此方法将清除当前在密钥缓冲区中的所有密钥,并返回已清除的密钥数量。然后,您可以在测试中使用它,如 if(clearKeyBuffer()) 来测试自上次测试以来是否按下了某个键。

    至于你的程序流程,你有很多额外的东西。你可以去掉大部分,但功能上仍然相同:

    do {
        notDeadAnimation();
        usleep(200000);
    } while(clearKeyBuffer());
    
    deadAnimation();
    

    然而,这有一个明显的问题,有人可以只是

    【讨论】:

    • 请注意,conio.h 可能仅限于 Windows。
    猜你喜欢
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    • 2010-09-09
    相关资源
    最近更新 更多