What is minesweeper?
Minesweeper is a popular game that was included in the Windows operating system. The aim is to discover the mines. Each tile of the map is either a mine or a number saying how many mines are adjacent to the tile.
Method
The method I use is to initialize the map with 0 values on every tile. The different values that can have a tile are:
1 2 |
-1 : A mine is on the tile 0, 1, ..., n: N mines are close to the tile |
We check that the number of mines can be placed in the map.
While we don’t have placed the number of mines, we generate a random x and y where we want to place the mine.
If the x,y position is not a mine, we place a mine and increment the adjacent tiles.
Code
Each spot on the map is called a Tile. A tile can have different values (type). We could have only made the map an two dimension array of int but because we may had different objects/bonus in the future I prefer to implement it as an extensible object.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class Tile { private int type = 0; public int getType() { return type; } public void setType(int type) { this.type = type; } } |
A map is an object containing an two dimensions array of tiles.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
public class Map { private int width; private int height; private int nMines; private Tile[][] map; public Map(int w, int h, int n) { this.width = w; this.height = h; this.nMines = n; this.map = new Tile[w][h]; for (int i = 0; i < this.width; i++) { for (int j = 0; j < this.height; j++) { map[i][j] = new Tile(); } } generate(); } private void increment(int x, int y) { if (x >= 0 && x < width) { if (y >= 0 && y < height) { if (map[x][y].getType() != -1) map[x][y].setType(map[x][y].getType() + 1); } } } private void generate() { if (nMines > width * height) { //if they are too many mines ofr the map we set the ratio of mines to 1/4 nMines = width * height / 4; } Time t = new Time(); t.setToNow(); //set the seed Random r = new Random(t.toMillis(false)); int n = 0; int x, y; while (n < nMines) { x = r.nextInt(width); y = r.nextInt(height); if (map[x][y].getType() != -1) { map[x][y].setType(-1); //Update the adjacent tiles increment(x - 1, y - 1); increment(x - 1, y); increment(x - 1, y + 1); increment(x, y + 1); increment(x, y - 1); increment(x + 1, y - 1); increment(x + 1, y); increment(x + 1, y + 1); n++; } } } public Tile get(int x, int y) { return (map[x][y]); } public int getWidth() { return width; } public int getHeight() { return height; } public int getnMines() { return nMines; } } |
The interesting method is generate() and increment().
Conclusion
This is a pretty straight forward method of generating a map. An alternative would have been to place every mines and generate the tile number after.
Leave a Reply