I’m taking a C refresher and took on a board game as an exercise. The board game is “Game of the Generals” and is pretty much like chess as it uses pieces with ranks on an 8×8 square.
Basically the implementation of a board is a two-dimensional array of a particular struct. So a square of the board can be accessed through its indices, much like an x-y coordinate system.
Now I decided to randomly distribute the pieces across the board, and the logic is to generate a random x-y coordinate, check if a piece already resides on those coordinates on the board, and populate it with a piece if it is available. If it is not, then another random x-y coordinate is generated. This goes on until all pieces are accounted for.
I’m using rand() to generate random numbers within a specific range (I’m using a modulo operator and a padding number to dictate the range. See code below)
But rand() doesn’t seem to give random enough numbers for me to work with. I keep ending up with the same piece distribution over and over again! (But interesting enough, I can generate a different distribution on a Mac, but the distribution is still consistent!)
See code below as to how I’m using rand() to generate a number with a range.
void initPieces(){
int player, rank_index, population, rand_min, rand_x, rand_y;
for(player = 1; player <= 2; player++){
if(player == 1){
rand_min = 5;
}else{
rand_min = 1;
}
for(rank_index = 0; ir < sizeof ranking/sizeof ranking[0]; rank_index++){
for(population = 0; population < getRank(rank_index)->population; population++){
do{
rand_x = (rand() % 8) + 1;
rand_y = (rand() % 4) + rand_min;
}while((getGrid(rand_x,rand_y))->has_piece == 1);
assignPiecetoGrid(player,rank_index,rand_x,rand_y);
}
}
}
}
You need to realize that
rand()is a pseudorandom number generator, and it is specifically engineered to return the same sequence of numbers for a given seed. The seed is set with thesrand()function.So, the way to make it less predictable is generally to re-seed it from something a bit more random, or at least from something that is not the same every time you run the program:
srand(time(NULL));