Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help with a method to randomly lay mines in a minesweeper game

Tags:

java

So my Java minesweeper game is represented as a int[][] where -1 represents a mine. When I initialize my game I need to randomly place x amount of mines.

What is an elegant way of doing this? I was thinking of using an ArrayList with the coordinates of each cell, randomly selecting it, changing the state of the int[][] and then removing that Point. This would ensure that no point is selected twice.

Is there a more elegant way of doing this?

like image 627
kontrarian Avatar asked Sep 07 '25 10:09

kontrarian


1 Answers

I'd do it similarly, but slightly differently. Use the card-dealing algorithm.

Create an array of all the coordinates in your grid, in order. ([0,0], [0,1] .. [0,max], [1,0] .. [max, max]). Then "shuffle the deck" by iterating the list in order and swapping each element with a random element. Then select the first x elements in the list and place mines in those locations.

like image 51
Mason Wheeler Avatar answered Sep 09 '25 01:09

Mason Wheeler