I have a C++ code here that will make a game where it will generate random number base on keyboard input, if the number is even, score will increase. If the score is 10, you win and you can restart or exit the game.
using namespace std;
int score = 0, run = 1;
char inp = 'z';
void the_game() {
int x = 0;
while (run) {
if ('a' <= inp && inp <= 'j') {
srand((unsigned)time(NULL));
x = (rand() % 11) * 2; //if 'a' <= inp <= 'j', x is always even
cout << "Number: " << x << endl;
}
else { // and if not, x is random
srand((unsigned)time(NULL));
x = (rand() % 11);
cout << "Number: " << x << endl;
}
if (x % 2 == 0) {
score++;
cout << "Current Score: " << score << "\n";
}
if (score == 10) {
run = 0;
cout << "You Win! press R to restart and others to exit" ;
}
Sleep(1000);
}
}
void ExitGame(HANDLE t) {
system("cls");
TerminateThread(t, 0);
}
In main, I use a thread to run the game while taking input from keyboard like below
int main() {
thread t1(the_game);
HANDLE handle_t1 = t1.native_handle();
cout << "The we_are_even game\n";
while (true) {
inp = _getch();
if (run == 1)
ResumeThread(handle_t1);
else{ //run == 0
if (inp == 'r') {
system("cls");
cout << "The we_are_even game\n";
run = 1; //restart game
}
else { //if inp != 'r', exit the game
ExitGame(handle_t1);
t1.join();
return 0;
}
}
}
}
The problem is, after i win the game and press 'r' to restart, the thread do not run again although it should be resumed. Where did i make a mistake here? How can i fix it? I have tried to suspend it when run = 0 and resume again but to no avail.