c语言猜拳游戏

#define _CRT_SECURE_NO_WARNINGS 1
#include 
#include 
#include 

// 定义猜拳选项
#define ROCK 1
#define PAPER 2
#define SCISSORS 3

// 玩家出拳
int getPlayerChoice() {
    int choice;
    printf("请选择出拳(1-石头;2-剪刀;3-布):");
    scanf("%d", &choice);
    return choice;
}

// 电脑随机出拳
int getComputerChoice() {
    static unsigned int seed = 0;
    seed++;
    srand((unsigned)time(NULL) + seed * seed);
    return (rand() % 3) + 1;
}

// 判断胜负并输出结果
void determineWinner(int player, int computer) {
    if (player == computer) {
        printf("平局!\n");
    }
    else if ((player == ROCK && computer == SCISSORS) ||
        (player == SCISSORS && computer == PAPER) ||
        (player == PAPER && computer == ROCK)) {
        printf("恭喜,你赢了!\n");
    }
    else {
        printf("很遗憾,你输了!\n");
    }
}

int main() {
    int playerChoice, computerChoice;

    // 使用当前时间初始化随机数种子
    srand(time(NULL));

    while (1) {
        playerChoice = getPlayerChoice();
        if (playerChoice < 1 || playerChoice > 3) {
            printf("输入无效,请重新选择出拳!\n");
            continue;
        }

        computerChoice = getComputerChoice();

        printf("你出了:");
        switch (playerChoice) {
        case ROCK:
            printf("石头\n");
            break;
        case PAPER:
            printf("布\n");
            break;
        case SCISSORS:
            printf("剪刀\n");
            break;
        }

        printf("电脑出了:");
        switch (computerChoice) {
        case ROCK:
            printf("石头\n");
            break;
        case PAPER:
            printf("布\n");
            break;
        case SCISSORS:
            printf("剪刀\n");
            break;
        }

        determineWinner(playerChoice, computerChoice);

        char playAgain;
        printf("是否再玩一局?(y/n):");
        scanf(" %c", &playAgain);
        if (playAgain != 'y') {
            break;
        }
    }

    return 0;
}

运行结果如下所示:

c语言猜拳游戏_第1张图片

你可能感兴趣的:(c语言,游戏,算法)