How can I improve performance in this Minesweeper algorithm?

I am currently doing a clone of Minesweeper. I made an algorithm that, by clicking on a plate with 0 surrounding mines, shows all neighbors with 0 surrounding mines, and then all of their neighbors with 0 surrounding mines ... (recursion). This result requires only one click:

It works as it should, but it is too slow. The original Minesweeper shows these tiles instantly, but in my case they have a slight delay between the readings.

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 - an array of arrays that has 8 position offsets for 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 do it faster?

+4
source share
2 answers

Use the SuspendLayout method to draw only when necessary:

* false by default for the designer, find out what it means

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

ALSO - avoid abuse of the Exception mechanism; this is not an effective and bad practice.

use a wall instead (an extra tile at the end of the matrix indicating .. well .. a wall).

+3
source

I guess RevealNeighbor is actually redrawing the Council. Instead, you should figure out what will be shown, and only then redraw the tip.

+1
source

All Articles