c语言剪刀石头布代码程序
时间: 2024-12-13 08:19:06 浏览: 53
在C语言中编写一个简单的剪刀、石头、布游戏(Rock-Paper-Scissors)的代码示例可能会包含以下几个步骤:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义游戏选项
enum GameOption { ROCK = 0, PAPER, SCISSORS };
// 游戏规则函数
int compareOptions(int playerChoice, int aiChoice) {
switch (playerChoice) {
case ROCK:
if (aiChoice == PAPER)
return -1; // 玩家输,因为纸包住石头
else if (aiChoice == SCISSORS)
return 1; // 玩家赢,因为剪刀剪石头
break;
case PAPER:
if (aiChoice == SCISSORS)
return -1; // 玩家输,因为布包住剪刀
else if (aiChoice == ROCK)
return 1; // 玩家赢,因为纸可以破石头
break;
case SCISSORS:
if (aiChoice == ROCK)
return 1; // 玩家赢,因为剪刀剪石头
else if (aiChoice == PAPER)
return -1; // 玩家输,因为布包住剪刀
break;
default:
printf("Invalid choice! Please enter 0 for Rock, 1 for Paper, or 2 for Scissors.\n");
return -1; // 处理无效输入
}
}
int main() {
enum GameOption playerChoice, aiChoice;
printf("Enter your choice (0: Rock, 1: Paper, 2: Scissors): ");
scanf("%d", &playerChoice);
// 随机生成AI的选择
srand(time(0));
aiChoice = (rand() % 3); // 从0到2随机选取
// 比较并输出结果
int result = compareOptions(playerChoice, aiChoice);
if (result == 1)
printf("You chose %s and AI chose %s. You win!\n", gameOptions[playerChoice], gameOptions[aiChoice]);
else if (result == -1)
printf("You chose %s and AI chose %s. You lose!\n", gameOptions[playerChoice], gameOptions[aiChoice]);
else
printf("It's a tie!\n");
return 0;
}
// 游戏选项枚举类型转换为字符串数组,方便打印
const char* gameOptions[] = {"Rock", "Paper", "Scissors"};
```
这个程序首先定义了游戏选项和比较函数,然后通过用户输入获取玩家选择,利用随机数生成AI的选择,最后根据游戏规则判断胜负并输出结果。
阅读全文
相关推荐


















