I am currently making a Minesweeper clone.
I made an algorithm that, when clicked on a tile with 0 surrounding mines, reveals all neighbors with 0 surrounding mines then all neighbors of them with 0 surrounding mines… (recursion).
This result only needs one click:

It works like it should but it is too slow. The original Minesweeper reveals these tiles instantly, but in my case, they have a little delay between the reveals.
I wrote this code:
private void RevealNeighbor(int x, int y) {
foreach(var neighbor in _neighbors) {
try {
Tile tile = _tiles[x + neighbor[0], y + neighbor[1]];
if(tile.TileType == TileType.Empty && tile.Hidden) {
tile.Reveal();
if(tile.Number == 0) {
RevealNeighbor(x + neighbor[0], y + neighbor[1]);
}
}
}
catch(IndexOutOfRangeException) {
}
}
}
_neighbors is an array of arrays, that has the 8 position offsets for the neighbors:
private readonly int[][] _neighbors = new[] {
new[] {-1, -1},
new[] {0, -1},
new[] {1, -1},
new[] {1, 0},
new[] {1, 1},
new[] {0, 1},
new[] {-1, 1},
new[] {-1, 0}
};
How can I make it faster?
Use the SuspendLayout method, to draw only when needed:
*false is a default for the designer, find out what it means
ALSO – avoid abusing the Exceptions mechanism, it is not efficient and bad practice
instead use a wall (extra tile on the end of the matrix indicating.. well.. a wall).