C语言设计一个石头剪刀布游戏。要求1.开始可以选择三轮两胜或五轮三胜。2,每一轮中,玩家输入自己的选择,计算机随机生成选择。在每一轮中有10秒倒计时,玩家可以看见剩余几秒,若超时则判断超时,输了。3定义石头剪刀布,若输入其他则提示重新输入。4.最后统计输赢平局的轮数
时间: 2025-01-05 18:38:35 浏览: 80
在C语言中设计一个石头剪刀布游戏,我们可以按照以下步骤进行:
首先,我们需要定义三个选项:石头、剪刀、布,并设置它们的数字代表,例如`0`代表石头,`1`代表剪刀,`2`代表布。
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
enum Choices { STONE = 0, SCISSORS = 1, PAPER = 2 };
int get_user_choice() {
int choice;
while (1) {
printf("请输入(0-石头, 1-剪刀, 2-布): ");
scanf("%d", &choice);
if (choice >= 0 && choice <= 2) {
break;
}
printf("输入错误,请重新选择!\n");
}
return choice;
}
int computer_choice() {
srand(time(NULL));
return rand() % 3;
}
void play_round(int user, int computer) {
time_t start_time;
clock_t end_time;
start_time = clock();
while (clock() - start_time < CLOCKS_PER_SEC * 10) {
// 模拟10秒倒计时
printf("剩余时间: %.2fs\n", ((double)(CLOCKS_PER_SEC * 10 - (clock() - start_time)) / CLOCKS_PER_SEC));
sleep(1); // 程序暂停一秒
}
if (clock() - start_time > CLOCKS_PER_SEC * 10)
printf("您超时了!\n");
switch ((user + computer) % 3) {
case 0:
printf("平局!双方都选择了%d\n", user);
break;
case 1:
if (user == SCISSORS && computer == PAPER)
printf("你赢了!剪刀战胜了布。\n");
else
printf("电脑赢了!%d战胜了%d。\n", computer_names[computer], user_names[user]);
break;
case 2:
if (user == STONE && computer == SCISSORS)
printf("你赢了!石头砸烂了剪刀。\n");
else
printf("电脑赢了!%d战胜了%d。\n", computer_names[computer], user_names[user]);
break;
}
}
int main() {
const char* user_names[] = {"石头", "剪刀", "布"};
const char* computer_names[] = {"石头", "剪刀", "布"};
int rounds = 5; // 默认五轮三胜制
int win_count = 0, lose_count = 0, tie_count = 0;
for (int i = 0; i < rounds; i++) {
printf("第%d轮比赛开始...\n", i+1);
int user = get_user_choice();
int computer = computer_choice();
play_round(user, computer);
if (user == computer)
tie_count++;
else if (user_names[user] == computer_names[computer])
lose_count++;
else
win_count++;
printf("\n当前战绩: 胜%d, 平%d, 负%d\n", win_count, tie_count, lose_count);
}
if (win_count > lose_count)
printf("恭喜你赢得了比赛!\n");
else if (lose_count > win_count)
printf("很遗憾,你输了这场比赛!\n");
else
printf("平局,双方打成平手!\n");
return 0;
}
```
在这个代码示例中,我们首先定义了用户和电脑的选择以及对应的名称。然后实现了获取用户选择、电脑随机选择以及单轮游戏的函数。`main()`函数中控制游戏的轮数,并根据胜负情况更新分数,最后根据结果给出相应的提示。
阅读全文
相关推荐

















