I am working on a Minesweeper game in C, and I am facing an issue with the rand() function producing repeating patterns when placing mines on the game board. My code initializes the game field and places mines at random positions, but the randomness seems to be not truly random or starts repeating after some time. Here is the relevant part of my code:
srand(time(NULL);
is in the main function.
void logic_fill_c(int width, int height, char **field, int numb_of_mine)
{
logic_place_mine(width, height, field, numb_of_mine);
logic_place_numb(width, height, field);
}
void logic_place_mine(int width, int height, char **field, int numb_of_mine)
{
int x, y;
do{
x = rand() % width;
y = rand() % height;
if (field[x][y] != MINE) {
field[x][y] = MINE;
numb_of_mine--;
}
} while(numb_of_mine != 0);
}
void logic_place_numb(int width, int height, char **field)
{
int i, j;
for (i = 0; i < width; i++) {
for (j = 0; j < height; j++) {
if (field[i][j] != MINE) {
field[i][j] = logic_count_surounding_bombs(width, height, field, i, j) + '0';
}
}
}
}
Example Matrix after filling
GitHubRepo Complete Code
What did you try?
I have tried using the rand() function to generate random positions for placing mines on the game board. However, I did not include any seeding for the random number generator. I expected rand() to produce different random sequences on each run, but the results often seem repetitive.
What were you expecting?
I expected that the mines would be placed in different positions each time I run the program, providing a truly random layout for each game. I am looking for a way to ensure that rand() generates a unique sequence of random numbers every time the program is executed.
My Questions:
How can I ensure that rand() produces truly random numbers every time the program runs?
Are there any best practices for seeding the random number generator in C to avoid repeating patterns?
Any help or suggestions would be greatly appreciated!
Moritz is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1