使用C++编写一个简单游戏程序
时间: 2024-04-30 12:20:46 浏览: 92
好的,我可以给您提供一个简单的 C++ 控制台游戏示例,名为“石头剪刀布”:
```cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int player, computer;
int player_score = 0, computer_score = 0;
const int ROCK = 1, SCISSORS = 2, PAPER = 3;
srand(time(nullptr)); // 初始化随机数种子
cout << "这是一个石头剪刀布小游戏!" << endl;
while (true)
{
cout << endl << "请选择(1-石头,2-剪刀,3-布,0-退出):";
cin >> player;
if (player == 0) // 退出游戏
break;
computer = rand() % 3 + 1; // 生成电脑的选择
cout << "您的选择为:";
switch (player)
{
case ROCK:
cout << "石头";
break;
case SCISSORS:
cout << "剪刀";
break;
case PAPER:
cout << "布";
break;
default:
cout << "无效的选择";
break;
}
cout << ",电脑的选择为:";
switch (computer)
{
case ROCK:
cout << "石头";
break;
case SCISSORS:
cout << "剪刀";
break;
case PAPER:
cout << "布";
break;
}
// 判断胜负
if (player == computer)
{
cout << endl << "平局!" << endl;
}
else if (player == ROCK && computer == SCISSORS ||
player == SCISSORS && computer == PAPER ||
player == PAPER && computer == ROCK)
{
cout << endl << "您赢了!" << endl;
player_score++;
}
else
{
cout << endl << "您输了!" << endl;
computer_score++;
}
cout << "当前得分:您 " << player_score << " : " << computer_score << " 电脑" << endl;
}
cout << endl << "游戏结束!" << endl;
return 0;
}
```
这是一个非常简单的游戏,玩家和电脑分别选择石头、剪刀、布,判断胜负并记录得分。希望您能够通过这个示例了解 C++ 的基本语法,以及如何使用控制台进行简单游戏的制作。
阅读全文