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;
}
It wasn't until we put the total number of cases on paper with a pen... (as you can see from the linked demo) Assuming that the value was either muk = 0
, jji = 1
, par = 2
, or won.
0-1
, 1-2
, and 2-0
win. I haven't proven it's a coincidence or a necessity yet...
It's a JavaScript code that has nothing to do with C, but I don't know if it's a reference.
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();
© 2024 OneMinuteCode. All rights reserved.