
雨夜思念为您分享以下优质知识
在C语言中实现猜拳游戏并统计成绩,可以通过以下步骤完成:
定义出拳规则
使用数组存储用户和计算机的出拳选项(如"石头"、"剪刀"、"布"),并通过随机数生成计算机的出拳。
实现胜负判断逻辑
根据猜拳规则判断胜负,通常使用以下逻辑:
- 石头胜剪刀,剪刀胜布,布胜石头(循环关系)。
统计成绩
使用计数器记录胜利、失败和平局的次数,游戏结束后输出总成绩。
用户交互设计
允许用户选择是否重新开始游戏,提供退出选项。
以下是一个完整的示例代码,综合了上述步骤:
```c
include
include
include
define MAX_ROUNDS 5
define WIN 1
define LOSE 0
define DANCE 2
// 函数声明
void displayRules();
int getHumanChoice();
int getComputerChoice();
int compareChoices(int human, int computer);
void displayResults(int wins, int losses, int dances);
void playRound();
int main() {
srand((unsigned)time(NULL)); // 初始化随机数种子
char *choices = {"石头", "剪刀", "布"};
int humanChoice, computerChoice;
int wins = 0, losses = 0, dances = 0;
int round = 0;
while (round < MAX_ROUNDS) {
displayRules();
humanChoice = getHumanChoice();
computerChoice = getComputerChoice();
printf("你出拳:%s,计算机出拳:%sn", choices[humanChoice], choices[computerChoice]);
int result = compareChoices(humanChoice, computerChoice);
if (result == WIN) {
printf("你赢了!n");
wins++;
} else if (result == LOSE) {
printf("计算机赢了!n");
losses++;
} else {
printf("打平!n");
dances++;
}
printf("当前战绩:胜=%d,负=%d,平=%dn", wins, losses, dances);
printf("是否继续?(y/n): ");
char response;
scanf(" %c", &response);
getchar(); // 清除换行符
}
displayResults(wins, losses, dances);
printf("游戏结束!n");
return 0;
}
// 显示游戏规则
void displayRules() {
printf("出拳规则:n");
printf("1. 石头胜剪刀,剪刀胜布,布胜石头(循环关系)n");
}
// 获取用户输入
int getHumanChoice() {
int choice;
printf("请输入你的出拳(1:石头 2:剪刀 3:布):");
scanf("%d", &choice);
while (choice < 1 || choice >
3) {
printf("输入错误!请输入1、2或3:");
scanf("%d", &choice);
}
return choice;
}
// 获取计算机出拳
int getComputerChoice() {
return rand() % 3;
}
// 比较出拳结果
int compareChoices(int human, int computer) {
if (human == computer) {
return DANCE;
} else if ((human - computer + 3) % 3 == 0) {
return WIN;
} else {
return LOSE;
}
}
// 显示最终结果
void displayResults(int wins, int losses, int dances) {
printf("n最终战绩:n");
printf("胜=%d,负=%d,平=%dn", wins, losses, dances);
if (wins >
losses) {
printf("恭喜你获胜!n");
} else if (losses >
wins) {
printf("计算机获胜!n");
} else {
printf("游戏以平局结束!n");
}
}
```
代码说明:
主函数
- 初始化随机数种子,设置游戏轮数(默认5局),并初始化胜负计数器。
- 通过循环进行每局游戏,调用相关函数获取用户输入和计算机出拳,并判断胜负。
- 每局结束后显示当前战绩,询问用户是否继续。
辅助函数
- `displayRules()`:显示游戏规则。
- `getHumanChoice()`:获取用户输入,并验证输入有效性。
- `getComputerChoice()`:生成计算机随机出拳。
- `compareChoices()`:根据出拳结果判断胜负。