




























接着前一篇文章,Minesweeper: GDI+ 初步实现,本文在代码结构上做一些改进,不涉及新的功能。
首先我们来看MineBoard类的Init方法:
public void Init(int rows, int columns, int mines)
{
if (rows <= 0 || columns <= 0 || mines >= columns * rows)
{
throw new ArgumentException();
}
cells
= new MineCell[rows, columns];
PlaceRandomMines();
UpdateNearbyMinesCount();
}
实际的游戏开发中,随机布局整个游戏区域的情况并不多,更为常见的还是从地图中读取。同时,为了实现游戏过程中保存当前的游戏进展,然后读取后继续,或者支持从网络上下载布局,以及同其他人分享等,需要将布局的功能移到MineBoard在之外。
调整后的代码如下:
public interface IMineBoardBuilder
{
int TotalMines { get; }
int MarkedMines { get; }
MineCell[,] BuildMineCells();
}
PlaceRandomMines(cells);
UpdateNearbyMinesCount(cells);
MineBoard的Init方法则重构为:
public void Init(IMineBoardBuilder builder)
{
cells = builder.BuildMineCells();
totalMines = builder.TotalMines;
makedMines = builder.MarkedMines;
status = GameStatus.NotStarted;
}
[Serializable]
public class BoardFileLoader : IMineBoardBuilder
{
private MineCell[,] cells;
private int totalMines;
private int markedMines;public int TotalMines { get { return totalMines; } }
public int MarkedMines { get { return markedMines; } }public MineCell[,] BuildMineCells()
{
return cells;
}
}
相应的,可以为MineBoard类添加保存游戏进展的功能。
在交互方面,也可作如下改进:
public void WalkNearByCells(int row, int col, MineWalkCallback callback, Predicate<MineCell> match)
{
if (IsValidCell(row, col))
{
callback(ref cells[row, col]);if (match(cells[row, col]))
{
for (int i = -1; i < 2; i++)
{
for (int j = -1; j < 2; j++)
{
if (i != 0 || j != 0)
{
WalkNearByCells(row + i, j + i, callback, match);
}
}
}
}
}
}public void DoAction(IMineBoardAction action)
{
action.Run(this);
}
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。