我这里有一段C++代码,可以做一个游戏,它会根据键盘输入生成随机数字,如果数字是偶数,分数就会增加。如果分数是10,你就赢了,你可以重新开始或者退出游戏。
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);
}
在主程序中,我使用一个线程来运行游戏,同时接受键盘输入,如下图所示。
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;
}
}
}
}
问题是,当我赢了游戏并按'r'重新开始后,线程没有运行,虽然它应该恢复。我在哪里犯了一个错误?我怎么才能解决这个问题?我试过在运行=0时暂停它,然后再恢复,但没有用。