【问题标题】:To control the input speed in c++ regarding getasynckeystate function在 c++ 中控制有关 getasynckeystate 函数的输入速度
【发布时间】:2020-05-11 14:43:50
【问题描述】:

我正在使用 c++ 中的 getasynckeystate 函数编写一个简单的俄罗斯方块程序。我想在 while 循环中控制我的输入速度,以使块不会快速移动。这是我的简单伪代码。

while(1)
{
   if(GetAsyncKeyState(0x41) & 0x8000) //when key input is 'a'
            {
                move tetrimino to the left;
            }
   Sleep(100);
}

但是,如果我使用睡眠功能来控制输入速度,由于睡眠功能的特性,它在执行睡眠功能时会忽略输入。我想要的是控制我的输入速度(不要移动得太快),同时不要忽略每个输入案例。除此之外,块应该在按下键的同时连续移动。我知道我不应该使用 sleep 函数来实现这个目标,但我无法弄清楚如何仅使用 getasynckeystate 函数来实现这一目标。我该如何实现?

【问题讨论】:

    标签: input keyboard sleep tetris


    【解决方案1】:

    解决方案是使用计时器,我为您制作了这个源代码,它将每秒检测一次按键并输出到控制台。您可以利用此方法来完成您想做的事情。它不使用睡眠,因此不会出现您的代码使用的问题。

    要测试代码,执行它并按住 C

    #include <Windows.h>
    #include <iostream>
    #include <chrono>
    
    int main()
    {
        using Clock = std::chrono::steady_clock;
        std::chrono::time_point<std::chrono::steady_clock> start;
        std::chrono::time_point<std::chrono::steady_clock> now;
        std::chrono::milliseconds duration;
    
        bool bInit = false;
    
        while (1)
        {
            if (!bInit)
            {
                start = now = Clock::now();
                bInit =true;
            }
            
            now = Clock::now();
            duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - start);
    
            if (duration.count() > 1000)
            {
                start = Clock::now();
                if (GetAsyncKeyState('C'))
                {
                    std::cout << "pressed each 1 second\n";
                }
            }
    
        }
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-17
      • 2012-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      相关资源
      最近更新 更多