Zeeshan Dhillon
Zeeshan Dhillon

Reputation: 19

How to reset kbhit()?

I am making typing game in which random alphabets falls down from top of screen to the bottom and user needs to press that key to get score. There are two nested loops use to make this falling effect. The outer while loop generates random alphabet and the random position on x-axis while the inner for loop increments y-axis coordinates and prints the characters for each y coordinate value to make it fall. Now the problem is that when I use kbhit() function in for loop to check if users have pressed any key or not, it returns false when user has not pressed any key. But when user presses a key for the first time, it returns true and user gets the score. But when kbhit() is called again for next random alphabet, it returns true whether or not user has hit keyboard or not because user pressed ket earlier. May be I need to clear the keyboard buffer but I don't know how to do that. Here is

 while (true) {
        ch = rand() % 26 + 65;
        xPos = rand() % (x_end - x_start - 1) + x_start + 1;
        for (int i = y_start + 1; i < y_end - 1 && !kbhit(); i++) {
            cur_pos.X = xPos;
            cur_pos.Y = i;
            SetConsoleCursorPosition(console_handle, cur_pos);
            Sleep(150);
            cout << " ";
            cur_pos.X = xPos;
            cur_pos.Y = i + 1;
            SetConsoleCursorPosition(console_handle, cur_pos);
            cout << ch;
            if (i == y_end - 2) {
                cur_pos.X = xPos;
                cur_pos.Y = i + 1;
                SetConsoleCursorPosition(console_handle, cur_pos);
                cout << ch;
                Sleep(150);
                cur_pos.X = xPos;
                cur_pos.Y = i + 1;
                SetConsoleCursorPosition(console_handle, cur_pos);
                cout << " ";

            }

        }

Upvotes: 0

Views: 2131

Answers (2)

ParashSaitama
ParashSaitama

Reputation: 1

use kbhit() to detect key press and if key is pressed use getch() to reset kbhit(). For example,

#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
char ch;
for (int i = 0; i < 100000; i++){
cout << i << endl;
if (kbhit()){
ch = '#';
getch();
}
else{
ch = '_';
}
cout << ch << endl;
usleep(100000);
gotoxy(0, 0);
}
}

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283634

The ReadConsoleInput documentation page tells you how to check whether input is available (wait on the console handle, potentially for zero time if you want to poll) and how to unqueue it (by calling ReadConsoleInput or FlushConsoleInputBuffer)

By using the console API exclusively, you'll avoid any desynchronization between that and kbhit(), particularly the case where there are only mouse events waiting, so kbit() returns false but you still would want to flush the queue.

Upvotes: 0

Related Questions