#include <iostream>
#include <cstdlib> // For rand() and srand()
#include <ctime> // For time()
using namespace std;
// 函数用于获取随机生成的手势(0为石头, 1为剪刀, 2为布)
int getAiChoice() {
return rand() % 3;
}
// 打印选择结果,参数分别为玩家选择和AI选择
void printChoices(int playerChoice, int aiChoice) {
const char* choices[3] = {"石头", "剪刀", "布"};
cout << "你出了: " << choices[playerChoice] << endl;
cout << "AI出了: " << choices[aiChoice] << endl;
}
// 判断胜负并输出结果
void determineWinner(int playerChoice, int aiChoice) {
if (playerChoice == aiChoice) {
cout << "平局!" << endl;
} else if ((playerChoice == 0 && aiChoice == 1) ||
(playerChoice == 1 && aiChoice == 2) ||
(playerChoice == 2 && aiChoice == 0)) {
cout << "你赢了!" << endl;
} else {
cout << "你输了!" << endl;
}
}
int main() {
srand(time(0)); // 初始化随机数种子
while (true) {
int choice;
cout << "请输入你的选择(0=石头, 1=剪刀, 2=布,-1退出游戏): ";
cin >> choice;
if (choice == -1) {
break;
}
if (choice >= 0 && choice <= 2) {
int aiChoice = getAiChoice();
printChoices(choice, aiChoice);
determineWinner(choice, aiChoice);
} else {
cout << "无效输入,请重新输入。" << endl;
}
}
cout << "游戏结束,感谢参与!" << endl;
return 0;
}
//这段代码定义了一个简单的命令行游戏循环,其中包含了一个与AI对手进行石头剪刀布对决的功能。AI的选择是通过随机函数生成的,因此每次运行时AI的选择都是不确定的。玩家通过输入数字来选择自己的手势,然后程序会显示双方的选择,并根据规则判断胜利者。如果想要退出游戏,只需输入-1即可。