用C语言写一个猜拳游戏
时间: 2023-08-31 19:38:07 浏览: 119
C语言实现猜拳游戏
5星 · 资源好评率100%
### 回答1:
好的,我可以回答这个问题。以下是一个简单的猜拳游戏的 C 语言代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int player, computer, result;
srand(time(NULL));
printf("欢迎来到猜拳游戏!\n");
printf("请出拳:1-石头,2-剪刀,3-布\n");
scanf("%d", &player);
computer = rand() % 3 + 1;
if (player == 1) {
if (computer == 1) {
result = ;
} else if (computer == 2) {
result = 1;
} else {
result = -1;
}
} else if (player == 2) {
if (computer == 1) {
result = -1;
} else if (computer == 2) {
result = ;
} else {
result = 1;
}
} else {
if (computer == 1) {
result = 1;
} else if (computer == 2) {
result = -1;
} else {
result = ;
}
}
if (result == ) {
printf("平局!\n");
} else if (result == 1) {
printf("你赢了!\n");
} else {
printf("你输了!\n");
}
return ;
}
### 回答2:
猜拳游戏是一种简单而有趣的游戏,可以使用C语言来实现。下面是一个基本的实现示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int player_choice, computer_choice;
int win_count = 0, lose_count = 0;
srand(time(NULL));
printf("欢迎来到猜拳游戏!\n");
while (1) {
printf("\n请选择:\n");
printf("1.剪刀\n");
printf("2.石头\n");
printf("3.布\n");
printf("0.退出\n");
scanf("%d", &player_choice);
if (player_choice == 0) {
break;
}
if (player_choice < 1 || player_choice > 3) {
printf("无效的选择,请重新选择!\n");
continue;
}
// 生成计算机随机选择
computer_choice = rand() % 3 + 1;
printf("你选择了:");
switch (player_choice) {
case 1:
printf("剪刀\n");
break;
case 2:
printf("石头\n");
break;
case 3:
printf("布\n");
break;
}
printf("计算机选择了:");
switch (computer_choice) {
case 1:
printf("剪刀\n");
break;
case 2:
printf("石头\n");
break;
case 3:
printf("布\n");
break;
}
// 判断胜负
if ((player_choice == 1 && computer_choice == 3) ||
(player_choice == 2 && computer_choice == 1) ||
(player_choice == 3 && computer_choice == 2)) {
printf("你赢了!\n");
win_count++;
} else if (player_choice == computer_choice) {
printf("平局!\n");
} else {
printf("你输了!\n");
lose_count++;
}
}
printf("游戏结束!\n");
printf("你的总胜利次数:%d\n", win_count);
printf("你的总失败次数:%d\n", lose_count);
return 0;
}
```
这个程序通过`rand()`函数生成计算机的随机选择,让玩家通过选择1-3进行猜拳(1表示剪刀,2表示石头,3表示布)。程序会判断玩家和计算机的选择,并输出胜负结果。退出游戏时,程序会统计玩家的胜利和失败次数,并输出到屏幕上。
阅读全文