I am trying to create a game with a c++ Console Application
My goal is to have my do .. while()
running while waiting for a response.
It should keep displaying "..O.." until the "a" key is pressed and then it displays instead ".O..." or when the "d" key is pressed shows "...O."
My problem is i cant use cin
or getline
without pausing the application to wait for input.
So is there a way for to do something like a loop where if a value is not returned by cin
in 10 milliseconds it prints "..O.." ?
I don't want the program to keep waiting for input, maybe like a Sleep(10)
between each cin
...
My Idea of how it should look:
void out()
{
int x;
string key;
do {
cin >> key;
//insert here something like break; that will
//stop waiting for input after 10 milliseconds.
system("cls");
if (key != "a" && key != "d") {
cout << "..O..";
}
else {
if (key == "a") {
cout << ".O..." << endl;
}
else {
if (key == "d") {
cout << "...O." << endl;
}
else {
cout << "..O..";
}
}
}
} while (x == 0);
x = 0;
}
Best thing to do is to implement GetAsyncKeyState()
which uses virtual key codes to check if a key is pressed.
The code would look like this:
bool end = false;
do {
system("cls");
cout << "..O..";
cin >> key; //output will remain same as long as no input
system("cls");
if (GetAsyncKeyState(VK_LEFT)) {
cout << ".O..." << endl;
}
else if (GetAsyncKeyState(VK_RIGHT) {
cout << "...O." << endl;
}
} while (!end); //remember to add a way to end the loop.
source: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getasynckeystate
List of Virtual Key Codes: https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes