用c++写一个游戏
时间: 2023-07-04 16:09:45 浏览: 66
好的,我可以为你提供一个简单的游戏代码示例,这个游戏是猜数字游戏。
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
// 生成随机数
srand(time(0));
int secretNum = rand() % 100 + 1;
// 游戏开始
cout << "欢迎来到猜数字游戏!" << endl;
cout << "我已经想好了一个1到100之间的整数。" << endl;
cout << "请猜一下这个数字是多少:" << endl;
int guess = 0;
int numGuesses = 0;
// 猜数字
while (guess != secretNum) {
cin >> guess;
numGuesses++;
if (guess < secretNum) {
cout << "你猜的数字太小了,请再试一次:" << endl;
} else if (guess > secretNum) {
cout << "你猜的数字太大了,请再试一次:" << endl;
}
}
// 游戏结束
cout << "恭喜你猜对了!" << endl;
cout << "你一共猜了" << numGuesses << "次。" << endl;
return 0;
}
```
这个游戏会生成一个1到100之间的随机整数,然后让玩家猜这个数字是多少。玩家每猜一次,程序会告诉他猜的数字是太大还是太小,直到玩家猜对为止。最后程序会告诉玩家猜了多少次才猜对了。