C++ real time snake like game console without multithreading - c++

I want to make snake game in console using c++, but I don't want to wait every "frame" for user input.
If i'll use cin or getch (), program will wait for player input every frame:
while (game)
{
c = getch (); //input
snake.move (c); //moving
draw (); //drawing
}
How to move snake and draw it in console and don't waiting for input every frame?
Is there any way to do that without multithreating?
Maybe something like put something in cin buffer in code instead of using console? Is it doable?

You can't use standard C++ because there is no guarantee that when the User presses a key, the key press will be acknowledged immediately. Many implementations wait for the Enter key to be pressed, then process the input buffer.
You will need an event driven system. You want the OS or hardware to notify your program that a key press event has occurred. In this kind of system, you would move the snake during the event handler.
Another method is to poll the switch status. When the key is released, you could move the snake.
All of the above solutions require platform or OS specific functionality.

Related

Qt C++: How to make a for loop until a button is pressed

I have been trying to make a GUI Blackjack game in C++ with Qt. However, I have hit a road block on my way. I made the game and the game logic last year in pure C++ (link below). I am trying to use the same code to build the GUI version of the game Github/Blackjack.
It's mostly done to the point that I have the cards showing up, adding the values of those cards, the dealer and the player set up.
In the C++ version I made a vector of all the players and added the dealer to the end of it, then using a for loop, I would iterate through the players to get them to play.
In Qt, I have created a widget with two buttons "Hit" and "Stand" for the player control.
"Hit" button is simple and connected the click event of the button with the hit member function of the player.
ctrl = new PlayerControl(nullptr, mainPlayer);
connect(ctrl->ui->hitButton, &QPushButton::clicked, [mainPlayer]{
mainPlayer->hit();
});
Code for iterating through the vector:
for (size_t i = 0; i < players.size(); i++)
{
if (i == playerPos - 1)
{
ctrl->setVisible(true);
//how to make the loop to pause here until the user presses the
//"Stand button", and then proceed with the rest of the loop?
}
else if (i == players.size() - 1)
dealerPlay();
else
computerPlay(players[i]);
}
I'll really appreciate any help. :)
I don't really understand the code you are showing or how it relates to the question in the title of your post. I'll just answer the question, which is:
How to make a for loop until a button is pressed
The answer is that you probably don't want to do that, because that would involve multi-threading or some kind of complicated concurrency mechanism. When you're writing a GUI, the main thread of your application usually sits in a loop waiting for event messages (like clicks and key presses) from the operating system. When it gets such a message, it is supposed to handle them quickly and then go back to waiting for the next message.
In Qt, you can handle these events by overriding functions in your QMainWindow class or by connecting Qt signals to slots.
So, instead of having a loop that iterates through each player and waits for them to make their move, you would have some long-living variables that keep track of the state of the game, and when you detect that a player has made a move (i.e. by clicking a button), you would update those variables, update any data shown on the screen, and then return from your event handler so you can handle the next event.

How do I get GETCH() like behaviour in C++ that is time based?

So I made a little game (console app) and at the end I wanna display an end game screen. If the player dies while trying to move somewhere they'll be in the middle of pressing a key. My solution that uses _getch() to halt the console will catch that key and instantly close the console without giving the player a chance to see what happened. It makes it look like the game crashed.
I need something time based, that doesn't react to any keys for a few seconds, but then does.
int main()
{
//game loop is here somewhere, exits when player is dead
if (player.isDead())
{
displayGameOverScreen();
return 0;
}
}
void displayGameOverScreen()
{
std::cout << "You died.";
_getch();//if player is still pressing keys
//console instantly closes
}
I assume you are working under Windows, so you can put Sleep(2000) for 2 seconds of sleep or better solution if you close the window when user press directly a button that reserved for, like 'Q' letter and 'R' is could be for retry / restart in this case, let the game re-initialise itself and remove return statement after displayGameOverScreen().
Problem with Sleep when the users press a key while in its sleeping, the key press will have effect immediately after sleep have done.
After displayGameOverScreen();
add system("pause");
and the screen should be frozen on the spot and will not close.
If that doesn't work, add Sleep(4000); instead of system("pause");
and it will stay for 4 seconds before closing.
Keep in mind that you should add #include<Windows.h>

How to Pause program inside a function until a user does something on the form

I am working on a project for my C++ Class and we are doing a poker program with AI and users. Using QT for the development.
What I need to do is inside of the function DECISION() if the player is not an AI, the program pauses until the user hits buttons to either fold, call, or Raise.
Basically I need to pause a program in the middle of executing a function, until the user presses a button. Then it will continue the rest of the function
if(Player[pp].ai == true){
//A bunch of code for AI decision making for folding, calling, raising.
}
else{ //If Player is NOT an AI
ENABLEUSERINPUT(true);
//Need to pause program here until the user has done something to the GUI
ENABLESERINPUT(false);
}
It's possible to wait for a user input using the QEventLoop
for example clicking on the button will exit the event loop.
//Need to pause program here until the user has done something to the GUI
QEventLoop oLoop;
// user click on button will release the event loop.
connect(pYoutrBtn , &QPushButton::clicked,
&oLoop, &QEventLoop::quit);
// wait.
oLoop.exec();

Close a program if a key is being pressed when opening it in osx

I'm trying to make a program that closes itself -or only runs the line of code that closes it- whenever a certain key is in the pressed state when the program is run, so, if I start the program and the 'c' key is pressed, the program must stop.
Note that cin or read doesn't help here, because it waits until you press enter to detect a keystroke. In a way, I'm looking for a way to detect the async key state(because the cursor may not be focused in the program's console window) in osx using c++.

How can I detect if any key is pressed by the user in C++ (console)?

I am writing a C++ CLI application how can I detect if any key is pressed by the user. I've seen that in c# but how can it be implement in c++
while(1)
{
while(/* code to check if any key is pressed*/)
{ //rest of the code
// sleep function
}
}
Hint: like in CLI games to move or to take certain action when a key is pressed or don't do any thing if no input is given.
On windows at least you could use GetKeyState
we can use _kbhit() function in c++. _kbhit is equal to 1 if any key is pressed. You have to clear the _kbhit buffer else it will remain 1. Method for clearing is character = getch(); This will save the last entered key in character which you can compare and decide which action to perform on which key.
While loop can be CPU consuming, i do not advice busy waiting method, instead you should think of event hooking.
Here you can read about winapi keystroke event hooking C++ Win32 keyboard events
If you are still interested to use the while loop, you should also free some resources by sleeping after checking that a condition is false (e.g. nanosleep )