#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
class NumberGuessingGame {
private:
int secretNumber;
int attempts;
int maxAttempts;
int minNumber;
int maxNumber;
bool gameOver;
int score;
public:
// 构造函数,初始化游戏参数
NumberGuessingGame(int min = 1, int max = 100, int attempts = 10)
: minNumber(min), maxNumber(max), maxAttempts(attempts) {
srand(time(0)); // 设置随机数种子
reset();
}
// 重置游戏
void reset() {
secretNumber = rand() % (maxNumber - minNumber + 1) + minNumber;
attempts = 0;
gameOver = false;
score = maxAttempts;
}
// 显示游戏欢迎信息
void displayWelcome() {
cout << "==================== 猜数字游戏 ====================" << endl;
cout << "我已经想好了一个 " << minNumber << " 到 " << maxNumber << " 之间的数字," << endl;
cout << "你有 " << maxAttempts << " 次机会猜出它。" << endl;
cout << "==================================================" << endl;
cout << endl;
}
// 获取用户猜测
int getGuess() {
int guess;
string input;
while (true) {
cout << "请输入你的猜测 (" << minNumber << "-" << maxNumber << "): ";
getline(cin, input);
// 尝试将输入转换为整数
try {
guess = stoi(input);
if (guess >= minNumber && guess <= maxNumber) {
break;
} else {
cout << "输入无效,请输入 " << minNumber << " 到 " << maxNumber << " 之间的数字。" << endl;
}
} catch (const invalid_argument&) {
cout << "输入无效,请输入一个整数。" << endl;
} catch (const out_of_range&) {
cout << "输入无效,数字超出范围。" << endl;
}
}
return guess;
}
// 检查猜测结果
bool checkGuess(int guess) {
attempts++;
score--;
if (guess < secretNumber) {
cout << "太小了!再大一点..." << endl;
return false;
} else if (guess > secretNumber) {
cout << "太大了!再小一点..." << endl;
return false;
} else {
cout << "恭喜你,猜对了!答案就是 " << secretNumber << "。" << endl;
cout << "你用了 " << attempts << " 次尝试。" << endl;
if (attempts == 1) {
cout << "太厉害了!一次就猜对了!" << endl;
}
score += maxAttempts - attempts; // 剩余次数越多,得分越高
cout << "你的得分是: " << score << endl;
return true;
}
}
// 检查是否还有剩余尝试次数
bool hasMoreAttempts() {
return attempts < maxAttempts;
}
// 显示游戏结束信息
void displayGameOver() {
if (!hasMoreAttempts() && !gameOver) {
cout << "游戏结束!你已经用完了所有尝试机会。" << endl;
cout << "正确答案是: " << secretNumber << endl;
cout << "你的得分是: " << 0 << endl;
}
}
// 运行游戏
void play() {
reset();
displayWelcome();
while (!gameOver && hasMoreAttempts()) {
int guess = getGuess();
gameOver = checkGuess(guess);
if (!gameOver && hasMoreAttempts()) {
cout << "你还剩下 " << maxAttempts - attempts << " 次尝试机会。" << endl;
cout << endl;
}
}
displayGameOver();
}
// 询问是否再玩一次
bool askToPlayAgain() {
char choice;
cout << "想再玩一次吗?(y/n): ";
cin >> choice;
cin.ignore(); // 清除输入缓冲区
return (choice == 'y' || choice == 'Y');
}
};
int main() {
NumberGuessingGame game(1, 100, 10);
do {
game.play();
} while (game.askToPlayAgain());
cout << "感谢游玩!再见!" << endl;
return 0;
}
1万+

被折叠的 条评论
为什么被折叠?



