I am writing a game in c++ that uses pdcurses to get input from the user and display continuously changing status of the player on the command line terminal. I use a while loop to continuously update the player's health (a number value), which is printed to the screen with a little status bar. It loops multiple times per second, which gives the game a real-time feeling. While the program is running, I want this value to be continuously updating even though I interact with the game. For example, I want to issue a command like "eat food" or "chop wood" without interrupting my little status display loop. I am having trouble designing the functionality of this part. How do I keep my status updating while I'm interacting with the game? I'm concerned that while the user is typing things into the terminal, the while loop is paused and the status no longer continues to update. I'm looking for some general pointers more than actual code. I really appreciate it. I'm pretty new to programming.
Do I have to use multiple threads or is there a way for the while loop to keep going while the user is entering text into the screen? Thank you for any pointers you can give. I hope this isn't too confusing of a question.
FWIW, here is the pseudocode I have so far:
#include //....some files....
int main() {
// Initialize game objects and graphics
bool programRunning = true;
float playerEnergy = 3000.0;
initscr(); /* Start curses mode */
while (programRunning)
{
// Display some graphics
// Display playerEnergy
// Set the while loop speed using std::this_thread::sleep_for...
playerEnergy -= 0.01;
int ch;
ch = getch();
switch (ch) {
case 'e': //eat food
playerEnergy += 1000;
// Do some stuff
break;
case 'w': //do some work
playerEnergy -= 1000;
// Do some stuff
break;
/* Etc, Etc. */
default:
break;
}
// If player quits, set programRunning to false
}
endwin(); /* End curses mode */
return 0;
}
As you suggested, multiple threads is the way I would go here.
I saw here that using getch
can solve your problem if you make it a non-blocking call using: nodelay(stdscr,TRUE);
but I haven't used that myself