石头剪刀布游戏

自己写的一个石头剪刀布游戏,如果有需要更改的地方请指出

#define _CRT_SECURE_NO_WARNINGS // scanf_s编写起来太过于麻烦,直接把这个警告关掉,便于编写。
#include 
#include 
#include 
// 定义猜拳选项
#define Rock 1
#define Paper 2
#define Scissors 3
void rules() {
    printf("欢迎参加剪刀石头布游戏\n石头:1,布:2,剪刀:3\n");//先进行游戏介绍
    printf("提醒:因为srand函数是秒级的,请注意输入数字的时候不要过快哦,不然就会导致电脑只出一个招式。\n");//提醒srand的注意事项
}
int choice() {
    int choice;
    if (scanf("%d", &choice) != 1 || choice < 1 || choice > 3) {
        printf("输入无效,请输入1到3的数字。\n");
        return -1;
    }
    return choice;
}
int comchoice() {
    srand((unsigned)time(NULL)); // 利用随机数保证每次电脑出的结果不同
    return rand() % 3 + 1; // rand % 3 的范围是0-2, 加1 是 1-3,满足猜拳范围。
}
void printChoice(int choice, const char* prefix) {
    switch (choice) {
    case Rock:
        printf("%s石头", prefix);
        break;
    case Paper:
        printf("%s布", prefix);
        break;
    case Scissors:
        printf("%s剪刀", prefix);
        break;
    }
}
int winner(int userChoice, int comChoice) {
    if (userChoice == comChoice) {
        printf("平局!你和电脑都出了 ");
        printChoice(userChoice, "");
        return 0; // 平局返回0
    }
    else if (((userChoice == Rock && comChoice == Scissors) ||
        (userChoice == Paper && comChoice == Rock) ||
        (userChoice == Scissors && comChoice == Paper))) {
        printf("你赢了!你出了 ");
        printChoice(userChoice, "");
        printf(",电脑出了 ");
        printChoice(comChoice, "");
        return 1; // 用户赢返回1
    }
    else {
        printf("你输了!你出了 ");
        printChoice(userChoice, "");
        printf(",电脑出了 ");
        printChoice(comChoice, "");
        return -1; // 用户输返回-1
    }
}
int main() {
    int totalgames, win, userwin = 0, comwin = 0;
    rules();
    while (1) { // 循环直至获取有效输入
        printf("请输入比赛局数(总局数必须为整数且为奇数): ");
        if (scanf("%d", &totalgames) != 1 || totalgames % 2 == 0) { // 检查输入是否为整数以及是否为奇数
            printf("无效输入,总局数必须为奇数。\n");//输入无效,循环继续
        }
        break; // 成功获取有效输入,退出循环
    }
    win = (totalgames / 2) + 1;
    for (int i = 0; i < totalgames;) {
        printf("\n第%d局开始:\n", i + 1);
        int userChoice, computerChoice, result;
        while ((userChoice = choice()) == -1); // 确保输入有效
        computerChoice = comchoice();
        result = winner(userChoice, computerChoice);
        if (result == 1) {
            userwin++;
            i++; // 只有当结果不是平局时才增加局数计数器
        }
        else if (result == -1) {
            comwin++;
            i++; // 同上
        }
        // 如果一方达到获胜条件,则提前结束
        if (userwin >= win || comwin >= win) 
            break;
    }
    printf("\n最终结果: ");
    if (userwin >= win) 
        printf("恭喜你赢得了比赛!");
    else if (comwin >= win) 
        printf("很遗憾,电脑赢得了比赛。");
    else 
        printf("比赛结束,未分胜负。");
    return 0;
}
}

石头剪刀布游戏_第1张图片
这是运行的结果。
可以自己写一写,很锻炼coding能力。

你可能感兴趣的:(游戏)