[英]How can i improve performance in this Minesweeper algorithm?
我目前正在制作掃雷克隆。 我做了一個算法,當點擊一個有0個周圍地雷的瓷磚時,會發現所有鄰居都有0個周圍的地雷,然后他們的所有鄰居都有0個周圍的地雷......(遞歸)。 此結果只需點擊一下:
它的工作原理應該如此,但它太慢了。 最初的掃雷隊員立刻展示了這些瓷磚,但就我而言,它們在揭示之間有一點延遲。
我寫了這段代碼:
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
是一個數組數組,它具有鄰居的8個位置偏移量:
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}
};
我怎樣才能讓它更快?
使用SuspendLayout方法,僅在需要時繪制:
* false是設計師的默認設置,找出它的含義
this.SuspendLayout();
... logic
this.ResumeLayout(false);
另外 - 避免濫用例外機制,這不是有效和不好的做法
而是使用一個牆 (矩陣末端的額外瓷磚表示......井......牆)。
我猜RevealNeighbor實際上重繪了董事會。 相反,你應該計算將被揭示的內容,然后重新繪制董事會。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.