I’m trying to make Minesweeper using JavaScript and I wanted to make a bit of code so that when you reveal a tile with no adjacent mines it reveals the tiles next to it. If any of those tiles also have no adjacent mines, they reveal their neighbouring tiles too. This should continue until you have revealed a field of tiles without adjacent mines and all of the tiles next to them.
Below is the function that runs when you click a tile.
mines
is a 2D array. If the value is 1 there is a mine.
minesNearby
is a 2D array where each value is the number of mines next to the tile at that position.
checkedTiles
is a 2D array. If the value is 1 the tile has been clicked.
findNeighbours
returns an array of all the positions of the tiles around a given tile. (e.g. [[19,5],[19,4],[19,3],[18,3]…)
updateTile
updates the tile div in the HTML.
function openTile(y,x) {
console.log(`opening tile y ${y} and x ${x}`)
checkedTiles[y][x] = 1;
updateTile(y,x);
if (mines[y][x] == 1) {
// death
} else if (minesNearby[y][x] == 0) {
findNeighbours(y,x).forEach((tile,index) => {
console.log(`${tile[0]}+${tile[1]}`)
if (checkedTiles[tile[0]][tile[1]] == 0) {
openTile(tile[0],tile[1])
};
});
}
}
This looks fine to me, but I’m sure there’s something I’m missing.
When you click a tile with no adjacent mines, it sometimes will reveal the tile to the top-left and sometimes will not reveal anything. (The top-left tile isn’t even the first in the indNeighbours
array).
If there are more tiles with no adjacent mines to the top left, a diagonal line of revealed tiles may occur.
How do I make this work properly?