I'm trying to make a mastermind game. The user has to guess the randomly generated colour.
I wrote the random method but it keeps starting with the same element, and the next 3 are
all the same but different from the first element (e.g I,o,o,o I,r,r,r
). How can I fix my code?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define cLength 6
int gen_rand();
// start of main
int main() {
int i, rNum;
// this is the array for the easy mode
char colours[cLength + 1] = {'r', 'o', 'y', 'g', 'b', 'i', 'v'};
// this is the randomly generated array
char rand[3 + 1] = "";
// this is the guess array that the user will populate
char guess[3 + 1] = "";
// for statement to populate the rand array with random elements in the colours array
rand[0] = colours[gen_rand()];
rand[1] = colours[gen_rand()];
rand[2] = colours[gen_rand()];
rand[3] = colours[gen_rand()];
printf("\n%c", rand[0]);
printf("\n%c", rand[1]);
printf("\n%c", rand[2]);
printf("\n%c", rand[3]);
// for statement to populate the guess array
for (i = 0; i < 4; i++) {
printf("\n Please enter a colour e.g r for Red : ");
scanf("%c", &guess[i]);
fflush(stdin);
}
printf("%c", guess[2]);
printf("\n\n\n");
system("pause");
}
int gen_rand() { // returns random number in range of 0 to 99
int r = rand() % 6;
srand(time(NULL));
return r;
}