模拟剪刀、石头和纸游戏,用s表示剪刀,r表示石头,p表示纸。游戏规则为:剪刀剪纸,石头砸剪刀,纸包石头。两名游戏者分别输入s、r或p,按照游戏规则输出结果C++语言流程图
时间: 2024-09-18 20:06:12 浏览: 41
课程大作业基于python开发的剪刀石头布游戏猜拳游戏源码.zip
在C++中创建一个简单的命令行模拟剪刀、石头、纸(Scissors, Rock, Paper)游戏,你可以使用switch语句来处理用户的选择并根据游戏规则判断胜负。以下是一个基本的流程图描述:
```cpp
1. 用户输入:提示玩家输入他们的选择(s for scissors, r for rock, p for paper)
2. 接收用户输入:使用cin获取玩家选择
3. 判断游戏结果:
a. 如果玩家出的是剪刀(s),对手如果是纸(p)则玩家输,否则平局
b. 如果玩家出的是石头(r),对手如果是剪刀(s)则玩家赢,否则平局
c. 如果玩家出的是纸(p),对手如果是石头(r)则玩家赢,否则平局
4. 输出结果:根据判断显示胜利者或平局
对应的C++代码如下:
```cpp
#include <iostream>
using namespace std;
int main() {
char userChoice, computerChoice;
// Step 1 & 2
cout << "Choose your move (s for scissors, r for rock, p for paper): ";
cin >> userChoice;
// Generate random computer choice
srand(time(0));
computerChoice = 's' + rand() % 3; // Random among s, r, and p
// Step 3: Switch case to determine winner
switch (computerChoice) {
case 's':
if (userChoice == 'p') {
cout << "Computer chose scissors. You win with paper!" << endl;
} else if (userChoice == 'r') {
cout << "Computer chose scissors. You lose with rock." << endl;
} else {
cout << "Computer chose scissors. It's a tie!" << endl;
}
break;
case 'r':
if (userChoice == 'p') {
cout << "Computer chose rock. You lose with paper." << endl;
} else if (userChoice == 's') {
cout << "Computer chose rock. You win with scissors!" << endl;
} else {
cout << "Computer chose rock. It's a tie!" << endl;
}
break;
case 'p':
if (userChoice == 's') {
cout << "Computer chose paper. You lose with scissors." << endl;
} else if (userChoice == 'r') {
cout << "Computer chose paper. You win with rock!" << endl;
} else {
cout << "Computer chose paper. It's a tie!" << endl;
}
break;
default:
cout << "Invalid input from the computer!" << endl;
return 1;
}
return 0;
}
```
阅读全文