用c++帮我写一个闯关小游戏,最少是三关,最多是五关
时间: 2024-03-23 09:41:35 浏览: 15
好的,这里给你一个简单的三关小游戏的示例代码,你可以根据需求进行修改:
```c++
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
int main() {
srand(time(NULL)); // 初始化随机数生成器
// 第一关
cout << "第一关:猜数字!" << endl;
int answer1 = rand() % 100 + 1; // 生成1-100之间的随机数
int guess1 = 0;
int tries1 = 0;
while (guess1 != answer1 && tries1 < 5) {
cout << "请输入一个1-100之间的整数:" << endl;
cin >> guess1;
tries1++;
if (guess1 < answer1) {
cout << "猜小了!" << endl;
} else if (guess1 > answer1) {
cout << "猜大了!" << endl;
} else {
cout << "恭喜你猜对了!" << endl;
}
}
if (tries1 >= 5) {
cout << "很遗憾,你没有在规定次数内猜对,游戏结束!" << endl;
return 0;
}
// 第二关
cout << "第二关:猜颜色!" << endl;
string colors[] = {"red", "blue", "green", "yellow"};
int answer2 = rand() % 4;
string guess2;
int tries2 = 0;
while (guess2 != colors[answer2] && tries2 < 5) {
cout << "请输入一种颜色(red/blue/green/yellow):" << endl;
cin >> guess2;
tries2++;
if (guess2 != colors[answer2]) {
cout << "猜错了!" << endl;
} else {
cout << "恭喜你猜对了!" << endl;
}
}
if (tries2 >= 5) {
cout << "很遗憾,你没有在规定次数内猜对,游戏结束!" << endl;
return 0;
}
// 第三关
cout << "第三关:猜单词!" << endl;
string words[] = {"apple", "banana", "orange", "grape", "watermelon"};
int answer3 = rand() % 5;
string guess3;
int tries3 = 0;
while (guess3 != words[answer3] && tries3 < 5) {
cout << "请输入一个水果名称:" << endl;
cin >> guess3;
tries3++;
if (guess3 != words[answer3]) {
cout << "猜错了!" << endl;
} else {
cout << "恭喜你猜对了!" << endl;
}
}
if (tries3 >= 5) {
cout << "很遗憾,你没有在规定次数内猜对,游戏结束!" << endl;
return 0;
}
// 通关
cout << "恭喜你完成了所有关卡,游戏结束!" << endl;
return 0;
}
```
这个示例代码包含了三个关卡,分别是猜数字、猜颜色和猜单词。每个关卡都有一个随机生成的答案,玩家需要在规定次数内猜对才能过关。你可以根据需要添加更多关卡或修改关卡的规则。