c++编写猜拳小游戏
时间: 2024-01-08 19:19:42 浏览: 120
以下是C++编写猜拳小游戏的示例代码:
```c++
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
int player; // 玩家出拳
int computer; // 电脑出拳
int result; // 比赛结果
// 生成随机数种子
srand(time(NULL));
// 电脑随机出拳
computer = rand() % 3 + 1;
// 玩家出拳
cout << "请出拳:1--石头,2--剪刀,3--布" << endl;
cin >> player;
// 判断玩家出拳是否合法
while (player != 1 && player != 2 && player != 3)
{
cout << "输入有误,请重新输入:";
cin >> player;
}
// 输出玩家和电脑出拳
cout << "你出了";
switch (player)
{
case 1:
cout << "石头。";
break;
case 2:
cout << "剪刀。";
break;
case 3:
cout << "布。";
break;
}
cout << endl;
cout << "电脑出了";
switch (computer)
{
case 1:
cout << "石头。";
break;
case 2:
cout << "剪刀。";
break;
case 3:
cout << "布。";
break;
}
cout << endl;
// 判断胜负
if (player == computer)
{
result = 0; // 平局
}
else if (player == 1 && computer == 2 || player == 2 && computer == 3 || player == 3 && computer == 1)
{
result = 1; // 玩家胜利
}
else
{
result = -1; // 电脑胜利
}
// 输出比赛结果
if (result == 0)
{
cout << "平局!" << endl;
}
else if (result == 1)
{
cout << "你赢了!" << endl;
}
else
{
cout << "你输了!" << endl;
}
return 0;
}
```
阅读全文