用c++实现石头剪刀布
时间: 2023-08-24 07:17:19 浏览: 106
c++石头剪刀布游戏控制台实现
好的,以下是一个简单的石头剪刀布游戏的C++代码示例:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
int playerScore = 0;
int computerScore = 0;
int roundNumber = 1;
cout << "欢迎来到石头剪刀布游戏!" << endl;
while (true) {
int playerChoice;
cout << "第 " << roundNumber << " 回合,请输入你的选择(1:石头,2:剪刀,3:布):";
cin >> playerChoice;
if (playerChoice < 1 || playerChoice > 3) {
cout << "无效的选择,请重新输入!" << endl;
continue;
}
int computerChoice = rand() % 3 + 1;
cout << "你的选择是:";
switch (playerChoice) {
case 1:
cout << "石头" << endl;
break;
case 2:
cout << "剪刀" << endl;
break;
case 3:
cout << "布" << endl;
break;
}
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;
playerScore++;
} else {
cout << "电脑赢了这一回合。" << endl;
computerScore++;
}
cout << "当前得分:你 " << playerScore << " - " << computerScore << " 电脑" << endl;
char playAgain;
cout << "是否再玩一局?(Y/N):";
cin >> playAgain;
if (playAgain == 'N' || playAgain == 'n') {
break;
}
roundNumber++;
}
cout << "游戏结束,最终得分:你 " << playerScore << " - " << computerScore << " 电脑" << endl;
return 0;
}
```
这个程序使用了一个while循环来实现多轮游戏的功能。在每个回合中,它会提示玩家输入选择,然后生成一个随机数来模拟电脑的选择。接下来,程序会比较玩家和电脑的选择,并根据胜负情况来更新得分。最后,程序会询问玩家是否想再次玩游戏,如果是则进入下一轮游戏,否则结束游戏。
阅读全文