帮我写一个c语言剪刀石头布小游戏代码
时间: 2023-09-11 14:08:59 浏览: 129
HTML5石头剪刀布手机微信小游戏代码.zip
好的,以下是一个简单的剪刀石头布小游戏的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int player_choice, computer_choice;
int player_score = 0, computer_score = 0;
char player_choice_name[10], computer_choice_name[10];
printf("欢迎来到剪刀石头布游戏!\n");
printf("游戏规则:\n");
printf("1. 剪刀胜利石头,石头胜利布,布胜利剪刀。\n");
printf("2. 每次出拳后会显示双方的选择和得分。\n");
printf("3. 游戏结束后会显示最终结果。\n");
while (1) {
// 玩家出拳
printf("\n请出拳:\n");
printf("1. 剪刀\n");
printf("2. 石头\n");
printf("3. 布\n");
scanf("%d", &player_choice);
// 生成电脑出拳
srand(time(NULL));
computer_choice = rand() % 3 + 1;
// 判断胜负
if ((player_choice == 1 && computer_choice == 3) ||
(player_choice == 2 && computer_choice == 1) ||
(player_choice == 3 && computer_choice == 2)) {
player_score++;
printf("你出了%s,电脑出了%s,你赢了!\n",
player_choice_name[player_choice - 1],
computer_choice_name[computer_choice - 1]);
} else if ((player_choice == 1 && computer_choice == 2) ||
(player_choice == 2 && computer_choice == 3) ||
(player_choice == 3 && computer_choice == 1)) {
computer_score++;
printf("你出了%s,电脑出了%s,你输了!\n",
player_choice_name[player_choice - 1],
computer_choice_name[computer_choice - 1]);
} else {
printf("你出了%s,电脑出了%s,平局!\n",
player_choice_name[player_choice - 1],
computer_choice_name[computer_choice - 1]);
}
// 显示得分
printf("当前得分:\n");
printf("你:%d 电脑:%d\n", player_score, computer_score);
// 判断是否继续游戏
printf("\n是否继续游戏?\n");
printf("1. 继续\n");
printf("2. 结束\n");
scanf("%d", &player_choice);
if (player_choice == 2) {
break;
}
}
// 显示最终结果
printf("\n游戏结束!\n");
printf("最终得分:\n");
printf("你:%d 电脑:%d\n", player_score, computer_score);
if (player_score > computer_score) {
printf("你获胜了!\n");
} else if (player_score < computer_score) {
printf("电脑获胜了!\n");
} else {
printf("平局!\n");
}
return 0;
}
```
注意,在上面的代码中,我使用了两个字符串数组来存储玩家和电脑的选择,以便在输出时显示选择的名称。如果你想要跑这个程序,请确保你的编译器支持C99标准,否则需要将这两个数组的定义放在函数的开头。
阅读全文