It's a minesweeper game. The objective here is to generate the exact number of mines. In this case I have an 8x8 grid of boxes with 10 mines (see at the bottom). So, the nested for loop generates 64 objects with x
and y
coordinates (for later drawing the grid) and a state
property to indicate whether the field is mined. Then, in generateBombs
I generate 10 objects with state:mined
with random x
and y
to overwrite 8 of the 64 objects in the boxes array randomly and thus plant the mines. The problem with my approach here is that there is a possibility of 2 non-unique pairs of x
and y
objects to be generated, and this way I'll end up with less than the original number of mines, because the same object will be overwritten twice. What is a good approach here?
Also, one of my requirements is for the generator to use a helper function for the mines, but they take the same arguments, the need might be defeated.
var minesweeper = {
boxes: [],
//rows
boxesNum: 0,
bombsNum: 0,
//creates a 8x8 grid
generateMap: function (width, height, bombsNum) {
for (i = 1; i < height; i++) {
this.boxes.push({
x: i,
y: 1,
state: "safe"
});
for (j = 1; j < width; j++) {
this.boxes.push({
x: 1,
y: j,
state: "safe"
});
}
}
this.generateBombs(width, height, bombsNum)
},
//mines random fields from the grid
generateBombs: function (width, height, bombsNum) {
for (k = 0; k < bombsNum; k++) {
this.boxes.push({
x: Math.floor(Math.random() * width + 1),
y: Math.floor(Math.random() * height + 1),
state: "mined"
});
}
}
}
minesweeper.generateMap(8, 8, 10);