首页 > 应用开发 > C/C++ > 回忆c++作业剪刀石头布
学习c++循环后,还记得老师布置的剪刀石头布,今天刷视频看到,又回顾一下
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
// 定义游戏选项枚举
enum Choice { Rock = 1, Paper, Scissors };
// 显示游戏规则
void showRules() {
cout << "===== 猜拳游戏规则 =====" << endl;
cout << "1. 输入 1 代表石头(Rock)" << endl;
cout << "2. 输入 2 代表布(Paper)" << endl;
cout << "3. 输入 3 代表剪刀(Scissors)" << endl;
cout << "=======================" << endl << endl;
}
// 获取玩家的有效输入
Choice getPlayerChoice() {
int input;
while (true) {
cout << "请输入你的选择(1-3): ";
cin >> input;
if (input >= 1 && input <= 3) {
return static_cast<Choice>(input);
}
cout << "输入无效,请重新输入!" << endl;
// 清除输入缓冲区防止死循环
cin.clear();
cin.ignore(1024, '\n');
}
}
// 生成电脑的随机选择
Choice getComputerChoice() {
return static_cast<Choice>(rand() % 3 + 1); // 生成1-3的随机数
}
// 判断胜负并返回结果
string determineWinner(Choice player, Choice computer) {
if (player == computer) {
return "平局!";
}
if ((player == Rock && computer == Scissors) ||
(player == Paper && computer == Rock) ||
(player == Scissors && computer == Paper)) {
return "你赢了!";
} else {
return "电脑赢了!";
}
}
// 主游戏循环
void playGame() {
char playAgain = 'y';
while (playAgain == 'y' || playAgain == 'Y') {
system("cls"); // 清屏(Windows),若为Linux/macOS需改为system("clear")
showRules();
Choice player = getPlayerChoice();
Choice computer = getComputerChoice();
cout << "\n你的选择: ";
switch (player) {
case Rock: cout << "石头"; break;
case Paper: cout << "布"; break;
case Scissors: cout << "剪刀"; break;
}
cout << " | 电脑的选择: ";
switch (computer) {
case Rock: cout << "石头"; break;
case Paper: cout << "布"; break;
case Scissors: cout << "剪刀"; break;
}
cout << endl;
cout << "结果: " << determineWinner(player, computer) << endl;
cout << "\n再玩一次?(y/n): ";
cin >> playAgain;
}
}
int main() {
srand(time(0)); // 初始化随机数种子
cout << "===== 欢迎来到猜拳游戏 =====" << endl;
playGame();
cout << "游戏结束,感谢游玩!" << endl;
return 0;
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70046748/viewspace-3087572/ ,如需转载,请注明出处,否则将追究法律责任。