简体   繁体   中英

How can i improve performance in this Minesweeper algorithm?

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

this.SuspendLayout();
... logic      
this.ResumeLayout(false);

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).

I'm guessing RevealNeighbor actually redraws the Board. Instead, you should compute what is going to be revealed and only then redraw the Board.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM