I am trying to create a minesweeper game and for the randomisation part I am having some trouble.
For perhaps a 10 by 10 grid minesweeper, I hope to achieve 10 or a specific number of bombs/mines randomly but am unsure of how to do it.
I have a 2D mines array that stores TRUE if it contains a bomb.
I know in a 1D array I could have the total number of elements divided up into n equal parts and then have one TRUE boolean element per part.
Ah, but it doesn't have to be equally distributed. I am also not very sure about lists, would using a list be a good way to solve this?
final int GRID_WIDTH = 10;
final int GRID_HEIGHT = 10;
final int BOMB_NUMBER = 10;
final boolean[][] minesArray = new boolean[GRID_WIDTH][GRID_HEIGHT];
for (int i = 0; i < BOMB_NUMBER; i++) {
//Get random position for the next bomb
Random rand = new Random();
int row = rand.nextInt(GRID_WIDTH);
int col = rand.nextInt(GRID_HEIGHT);
while(minesArray[row][col]) { //if this position is a bomb
//we get new position
row = rand.nextInt(GRID_WIDTH);
col = rand.nextInt(GRID_HEIGHT);
}
minesArray[row][col] = true; //make new position is a bomb
}