GamePieceCollection 类派生自泛型 List 类,并引入了方法以便更轻松地管理多个 GamePiece 对象。
创建代码
GamePieceCollection 类初始化私有成员 capturedIndex。 此字段用于跟踪哪些游戏块当前具有鼠标捕获。
#region PrivateMembersAndConstructor
private int capturedIndex;
public GamePieceCollection()
{
// No capture yet.
capturedIndex = -1;
}
#endregion
ProcessInertia 和 Draw 方法通过枚举集合中的所有游戏块并在每个 GamePiece 对象上调用相应的方法,简化了游戏 Game.Update 和 Game.Draw 方法所需的代码。
#region ProcessInertiaAndDraw
public void ProcessInertia()
{
foreach (GamePiece piece in this)
{
piece.ProcessInertia();
}
}
public void Draw()
{
foreach (GamePiece piece in this)
{
piece.Draw();
}
}
#endregion
在游戏更新过程中,也会调用 UpdateFromMouse 方法。 它通过首先查看当前捕获(如果有的话)是否仍有效,仅让一个游戏块具有鼠标捕获。 如果仍有效,则不允许其他游戏块检查捕获。
如果没有任何游戏块当前具有捕获,则 UpdateFromMouse 方法从最后向最前枚举每个游戏块,并查看该游戏块是否报告了鼠标捕获。 如果是这样,该游戏块成为当前捕获的游戏块,不再进行进一步处理。 UpdateFromMouse 方法首先检查集合中的最后一项,以便如果两个游戏块重叠,具有较高 Z 顺序的游戏块将获得捕获。 Z 顺序不是显式的,也不可更改;它只受游戏块添加到集合中的顺序控制。
#region UpdateFromMouse
public void UpdateFromMouse()
{
MouseState mouseState = Mouse.GetState();
// If there is a current capture and
// that piece still reports having the capture,
// then return. Another piece cannot have the capture now.
if (capturedIndex >= 0 &&
capturedIndex < Count
&& this[capturedIndex].UpdateFromMouse(mouseState))
{
return;
}
capturedIndex = -1;
// A higher numbered index gets first chance
// for a capture. It is "on top" of a lower numbered index.
for (int index = Count - 1; index >= 0; index--)
{
if (this[index].UpdateFromMouse(mouseState))
{
capturedIndex = index;
return;
}
}
}
#endregion