开发者

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

开发者 https://www.devze.com 2023-02-04 12:33 出处:网络
So my Java minesweeper game is represented as a int[][] where -1 represents a mine. When I initialize m开发者_开发技巧y game I need to randomly place x amount of mines.

So my Java minesweeper game is represented as a int[][] where -1 represents a mine. When I initialize m开发者_开发技巧y 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.


I would generate random coordinates and check the board for an existing mine. If it exists skip it and generate new coordinates, if it doesn't place a mine.


I assume the mine width is fixed?

If so then you could do it this way:

say you have a 4x4 mine grid.

Convert a decimal into binary, so for a 4bit the range would be:

2^4 = 16 => Range is 0...15

Then simply call this function for each grid "row":

1,16,0,3

would transform to:

0001
1111
0000
0011


This is in python. But it prints (x, y) coordinates of mines. Result is sorted, but it doesn't matter.

from random import sample
import sys

def randomSquares(n, m, mines):
  return sorted([ (mine % m, mine // n) for mine in sample(xrange(n * m), mines)])

if __name__ == '__main__':

  print randomSquares(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]))
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号