C++ 猜数字游戏:代码解析和测试
该程序是一个简单的猜数字游戏,功能说明如下:
-
用户可以设置游戏的时间限制,程序会提示用户输入时间限制,并将其保存在变量'timeLimit'中。
-
程序会生成一个随机的目标数字,目标数字的范围是1到10000之间。
-
游戏开始后,程序会提示用户猜一个数字,用户输入自己的猜测,并将猜测保存在变量'guess'中。
-
程序会根据用户的猜测与目标数字进行比较,如果猜测数字小于目标数字,则程序会提示用户猜测数字太低;如果猜测数字大于目标数字,则程序会提示用户猜测数字太高;如果猜测数字等于目标数字,则程序会提示用户猜测正确,并结束游戏。
-
程序会记录游戏开始的时间,并计算出已经过去的时间。如果已经过去的时间超过了用户设置的时间限制,程序会提示用户时间已经用完,并显示出目标数字。
-
游戏结束后,程序会询问用户是否要再次玩游戏,用户可以输入'Y'或'N'来选择。
下面是程序的测试截图:
- 设置时间限制为10秒,猜测正确:

- 设置时间限制为10秒,猜测错误:

- 设置时间限制为5秒,时间用完:

- 再次玩游戏:

代码解析
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
int min = 1;
int max = 10000;
int target;
int guess;
int timeLimit;
char playAgain;
srand(time(0)); // seed the random number generator
do {
// Setting game time
cout << "Enter the time limit for the game (in seconds): ";
cin >> timeLimit;
// Generating random target number
target = rand() % (max - min + 1) + min;
// Start game timer
time_t startTime = time(0);
time_t currentTime;
int elapsedTime;
cout << "Guess the number between " << min << " and " << max << endl;
// Game loop
do {
cout << "Enter your guess: ";
cin >> guess;
if (guess < target) {
cout << "Too low! Try again." << endl;
} else if (guess > target) {
cout << "Too high! Try again." << endl;
} else {
cout << "Congratulations! You guessed the correct number " << target << "." << endl;
break;
}
// Check time limit
currentTime = time(0);
elapsedTime = currentTime - startTime;
} while (elapsedTime < timeLimit);
// Game over
if (elapsedTime >= timeLimit) {
cout << "Sorry, you ran out of time. The correct number was " << target << "." << endl;
}
// Prompt for replay
cout << "Do you want to play again? (Y/N): ";
cin >> playAgain;
} while (playAgain == 'Y' || playAgain == 'y');
return 0;
}
原文地址: https://www.cveoy.top/t/topic/qjMe 著作权归作者所有。请勿转载和采集!