2

I'm making a game in C++ on Windows using the Console, which involves a turn-based battle. I'm using the Sleep() function to delay messages in the battle, which then advances when a key is hit. My problem is that while the game is "paused" by the sleep function, it still counts the user's key presses, and then starts using them.

For instance, if a user presses the "a" key four times while the game is sleeping, it will keep using that key press four times, long after it has been pressed.

How do I temporarily "turn off" the ability for the user's key presses to register with the program?

  • You can flush the input stream, as answered here: http://stackoverflow.com/questions/257091/how-do-i-flush-the-cin-buffer – vr.one Oct 21 '16 at 19:41
  • Just slurp the queue empty when you resume from the pause, keep calling getch while kbhit is true. Although it begs the question how you detect that you should unpause :) – Hans Passant Oct 21 '16 at 21:41

2 Answers2

0

AFAIK you can't turn that off but you can ignore keystrokes by instead have a loop that disregards all keystrokes

e.g.

time_t delay = 10;  // timeout delay
time_t start = time(NULL); // normally returns seconds

do
{
  if (_kbhit()) getch();
}
while (time(NULL) - start < delay);

of course you could do other things in your wait loop as well as well as check what key was pressed and then interrupt the while loop.

AndersK
  • 35,813
  • 6
  • 60
  • 86
0

_kbhit() and getch() are buffered function. Everything typed while asleep will be sent to the buffer and will be processed sequentially as soon as your function awakes to read new kb hits.

As unbuffered alternative, you can consider GetKeyboardState() to get the status of the keyboard at one specific moment. It's not buffered, so it's more adapted to your game.

Christophe
  • 68,716
  • 7
  • 72
  • 138