【发布时间】:2010-12-05 03:12:45
【问题描述】:
我正在开发游戏Baroque Chess 的爱好项目。没玩过的人,基本规则和国际象棋一样,只是走法和抓法不同。
我自然而然地为游戏创建了标准类:GameState、Board、Square,并为从 BasePiece 继承的每个部分指定了一个类。
每个部分都有 2 个主要的虚拟方法,GetPossibleMoves(Board board) 和 GetCapturedSquares(Board board, Square toSquare)。
现在,其中一个片段,the Imitator,通过“模仿”它捕获的片段来捕获片段。例如,Long Leaper 可以通过跳过它们来捕捉碎片。这意味着模仿者可以跳过敌人的长跳跃者来捕获他们(但不能跳过其他任何东西)。
我完成了除模仿者之外的所有作品的GetCapturedSquares() 功能(这绝对是最棘手的作品)。
我模仿者的基本算法是:
- 找到所有有敌方棋子的方格
- 对于每个敌方棋子...
- 在与模仿者相同的位置创建模拟作品
- 如果是模拟棋子移动到选定的方格,则查找有效捕获
- 验证敌方方格是否在捕获方格列表中
因为我已经为其他棋子的动作编写了代码,所以我想我只需实例化新棋子并根据敌人的棋子类型使用它们的GetCapturedSquares() 方法。为此,我设置了一个Dictionary,正如您在此处看到的,它将System.Type 映射到所述类型的实例化对象:
var typeToPiece = new Dictionary<Type, BasePiece>()
{
{typeof(Pincer), new Pincer() { Color = this.Color, CurrentSquare = this.CurrentSquare}},
{typeof(Withdrawer), new Withdrawer() { Color = this.Color, CurrentSquare = this.CurrentSquare }},
{typeof(Coordinator), new Coordinator() { Color = this.Color, CurrentSquare = this.CurrentSquare }},
{typeof(LongLeaper), new LongLeaper() { Color = this.Color, CurrentSquare = this.CurrentSquare }},
{typeof(King), new King() { Color = this.Color, CurrentSquare = this.CurrentSquare }},
};
//...
var possibleMoves = typeToPiece[enemySquare.Occupant.GetType()].GetPossibleMoves(board, toSquare);
这样做让我觉得内心很肮脏。创建一个将片段类型表示为字典键的enum 或string 是否更合适,还是真的没关系?有没有不同的方法来处理这个?我认为它的方式很好,但我很想听听你的想法。
【问题讨论】: