GamePieceCollection 클래스 만들기
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