C++ 石头剪刀布游戏:简单教程及代码示例
以下是用 C++ 编写的简单石头剪刀布游戏:
#include <iostream>
#include <ctime>
using namespace std;
int main() {
srand(time(0));
int playerChoice;
int computerChoice = rand() % 3 + 1;
cout << '石头剪刀布游戏' << endl;
cout << '1. 石头' << endl;
cout << '2. 剪刀' << endl;
cout << '3. 布' << endl;
cout << '请选择(输入相应的数字):';
cin >> playerChoice;
cout << '你选择了:';
switch (playerChoice) {
case 1:
cout << '石头' << endl;
break;
case 2:
cout << '剪刀' << endl;
break;
case 3:
cout << '布' << endl;
break;
default:
cout << '无效选择' << endl;
return 0;
}
cout << '电脑选择了:';
switch (computerChoice) {
case 1:
cout << '石头' << endl;
break;
case 2:
cout << '剪刀' << endl;
break;
case 3:
cout << '布' << endl;
break;
}
if (playerChoice == computerChoice) {
cout << '平局' << endl;
} else if ((playerChoice == 1 && computerChoice == 2) ||
(playerChoice == 2 && computerChoice == 3) ||
(playerChoice == 3 && computerChoice == 1)) {
cout << '你赢了!' << endl;
} else {
cout << '你输了!' << endl;
}
return 0;
}
这个程序首先使用srand函数和time函数来生成一个随机数种子,然后使用rand函数生成一个1到3之间的随机数,表示电脑的选择。
接下来,程序输出菜单供玩家选择。玩家可以输入1、2或3来选择石头、剪刀或布。程序会根据玩家的选择和电脑的选择来判断胜负,并输出结果。
注意:此程序只是一个简单的示例,并没有考虑输入错误或异常情况的处理。在实际应用中,你可能需要添加更多的代码来处理这些情况。
原文地址: https://www.cveoy.top/t/topic/mWoT 著作权归作者所有。请勿转载和采集!