C language rock-paper-scissors game (a phenomenon problem where the results are concentrated in two)

Asked 2 years ago, Updated 2 years ago, 47 views

Hello! We've implemented the problem of using enumeration to implement a game of rock-paper-scissors between computers and people. The computer's position was expressed using a random function, and when you input scissors, "I won," "I lost," and "I tied" are evenly spread out, but when you enter rocks and beams, the results are concentrated in two. (As shown in the image below)

I wonder if this phenomenon is the original, the random function of rand() is not executed properly, or the code is weird.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum RSP_game{Rock, Scissor, Paper, Fail};

int convert_enum(char *input) {
    char *RSP_str[] = {
        "Rock",
        "rock",
        "Rock, paper, scissors"
        "Scissor",
        "scissor",
        "Scissors"
        "Paper",
        "paper",
        "Po"
    };

    int result;

    for (int i = 0; i < 9; i++) {
        result = strcmp(input, RSP_str[i]);
        if (result == 0) {
            if (i == 0 || i == 1 || i == 2)
                return 0;
            else if (i == 3 || i == 4 || i == 5)
                return 1;
            else if (i == 6 || i == 7 || i == 8)
                return 2;
        }
    }

    if (result > 0 || result < 0)
        return 3;
}

int main(void)
{
    char user_input[10];
    enum RSP_game user_choice;
    int computer_choice = 0;

    do {
        computer_choice = rand()%3;
        printf("Choose between scissors, rock, and paper (exit:q):");
        scanf("%s", &user_input);

        if (user_input[0] != 'q') {
            user_choice = convert_enum(user_input);

            if (user_choice == 3) {
                printf ("Value is not valid).\n");
                continue;
            }

            if (user_choice == computer_choice)
                printf ("It's a tie."\n");
            else if (user_choice > computer_choice)
                printf("Won)\n";
            else
                printf("lost"\n");
        }
    } } while (user_input[0] != 'q');

    return 0;
}

c

2022-09-22 19:37

2 Answers

Perhaps if you use only the rand function, you get the same value regularly, not random.

For proper processing, use the sland function before using the rand function.

#include <time.h>
...
...
time_t t;
srand((unsigned) time(&t));
...
...
rand();


2022-09-22 19:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.