用c语言设计一个猜拳游戏,要求: (1) 电脑随机生成一个石头(0)/剪刀(1)/布(2) (2) 玩家自己输入一个石头(0)/剪刀(1)/布(2) (3) 3局两胜,输出最终获胜。
时间: 2024-10-20 17:07:07 浏览: 49
设计一个简单的猜拳游戏(Rock-Paper-Scissors)的C语言程序可以按照以下步骤:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h> // 用于获取当前时间作为随机数种子
// 定义游戏选项枚举
enum Gesture { ROCK = 0, SCISSORS = 1, PAPER = 2 };
// 计算胜负结果
int calculateWinner(enum Gesture computer, enum Gesture player) {
if (computer == player)
return 0; // 平局
else if ((player == ROCK && computer == SCISSORS) ||
(player == SCISSORS && computer == PAPER) ||
(player == PAPER && computer == ROCK))
return 1; // 玩家胜利
else
return -1; // 电脑胜利
}
int main() {
srand(time(0)); // 设置随机数种子
int game_count = 3;
int wins_player = 0, wins_computer = 0;
for (int i = 0; i < game_count; i++) {
printf("Game %d:\n", i + 1);
enum Gesture random_gesture = (enum Gesture)(rand() % 3); // 电脑随机出拳
enum Gesture player_gesture;
printf("Enter your choice (0: Rock, 1: Scissors, 2: Paper): ");
scanf("%d", &player_gesture);
int result = calculateWinner(random_gesture, player_gesture);
switch (result) {
case 1:
printf("You win!\n");
wins_player++;
break;
case -1:
printf("Computer wins!\n");
wins_computer++;
break;
case 0:
printf("It's a tie!\n");
break;
}
}
if (wins_player > wins_computer) {
printf("Player wins the series!\n");
} else if (wins_computer > wins_player) {
printf("Computer wins the series!\n");
} else {
printf("Series ends in a draw!\n");
}
return 0;
}
```
阅读全文