#include <iostream>
#include <ctime>
#include <cstdlib>
int main() {
// 初始化随机数生成器
std::srand(std::time(nullptr));
const char* CHOICES[] = {"石头", "剪刀", "布"};
const char* WINNER[] = {"平局", "你赢了", "电脑赢了"};
std::cout << "欢迎来到石头、剪刀、布游戏!" << std::endl;
std::cout << "请输入你的选择(0 = 石头,1 = 剪刀,2 = 布):";
int playerChoice;
std::cin >> playerChoice;
// 确保输入在有效范围内
while (playerChoice < 0 || playerChoice > 2) {
std::cout << "无效输入,请重新输入(0 = 石头,1 = 剪刀,2 = 布):";
std::cin >> playerChoice;
}
// 电脑随机出拳
int computerChoice = std::rand() % 3;
std::cout << "你选择了:" << CHOICES[playerChoice] << std::endl;
std::cout << "电脑选择了:" << CHOICES[computerChoice] << std::endl;
// 判断胜负
int winnerIndex = (playerChoice - computerChoice + 3) % 3; // 循环到0, 1, 2
std::cout << WINNER[winnerIndex] << std::endl;
return 0;
}
C++石头剪刀布游戏
这篇文章介绍了如何使用C++编写一个简单的命令行石头剪刀布游戏,包括用户输入验证和随机电脑选择,展示了基础的编程逻辑。
摘要由CSDN通过智能技术生成