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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With