今天,我想用电脑玩一个叫做石头剪刀布的游戏,因为平时也没人和我玩。所以我就打开的电脑,开始整活!
游戏规则及运作
在下面的程序里,输入1代表石头,输入2代表剪刀,输入3表示布,就这样,然后计算机根据时间生成一个随机数种子,然后根据这个随机数通过计算得到计算机出的手势,然后根据以下规则进行判断输赢。
界面
我们先
cout << "石头剪刀布游戏" << endl;
cout << "1. 石头" << endl;
cout << "2. 剪刀" << endl;
cout << "3. 布" << endl;
电脑的随机数
根据上面的描述,可知先用srand(time(0))来进行随机数种子的生成,然后,我们使用rand() % 3 + 1生成1到3的随机数。所以,计算机的随机数代码如下:
srand(time(0));//随机数种子
//在此放置其他代码
int computerChoice = rand() % 3 + 1;//本语句表示用computerChoice变量进行存储随机数数据,以便后面的计算和使用。
//最后面的比较判定代码
在这里,计算机随机出数字的代码就完成了。
玩家的选择输入
我们先在界面上显示游戏说明,以便玩家输入。
cout << "石头剪刀布游戏" << endl;
cout << "1. 石头" << endl;
cout << "2. 剪刀" << endl;
cout << "3. 布" << endl;
然后,我们需要一个变量g来存储玩家输入的数据,然后用switch-case进行比较,从而知道输入的是什么和输赢判定
代码如下:
// 玩家进行选择
cout << "请选择(输入数字1-3):";
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 == 3) ||
(PlayerChoice == 2 && computerChoice == 1) ||
(playerChoice == 3 && computerChoice == 2)
) {
cout << "你赢了" << endl;
}
else {
cout << "你输了" << endl;
}
然后上完整代码:
#include <iostream>
#include <ctime>
using namespace std;
int main() {
srand(time(0)); // 初始化随机数生成器
int playerChoice;
int computerChoice = rand() % 3 + 1; // 生成1到3之间的随机数
// 输出游戏规则
cout << "剪刀石头布游戏" << endl;
cout << "1. 剪刀" << endl;
cout << "2. 石头" << endl;
cout << "3. 布" << endl;
// 玩家进行选择
cout << "请选择(输入数字1-3):";
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 == 3) ||
(playerChoice == 2 && computerChoice == 1) ||
(playerChoice == 3 && computerChoice == 2)
) {
cout << "你赢了" << endl;
}
else {
cout << "你输了" << endl;
}
return 0;
}
好了,今天的文章到此为止,记得点赞加关注加粉丝。