1

I'm writing a simple tetris program using getasynckeystate function in c++. I want to control my input speed in while loop so that the block doesn't move quickly. Here's my simple pseudo code.

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

However, if I use Sleep function to control input speed, because of the characteristic of Sleep function, it ignores input when executing Sleep function. What I want is to control my input speed(not to move too fast), while not to ignore every input case. In addition to this, the block should move continuously while pressing the key. I know that I should not use sleep function to achieve this goal, but I couldn't figure out how to achieve this only using getasynckeystate function. How can I implement this?

ssbin4
  • 11
  • 1

1 Answers1

0

The solution is to use a timer, I made this source code for you which will detect a key press once every second and output to console. You can utilize this method to accomplish what you want to do. It doesn't use Sleep so it will not have the issue your code uses.

To test the code, execute it and hold 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;
}
GuidedHacking
  • 3,628
  • 1
  • 9
  • 59