Creating the GamePieceCollection Class

The GamePieceCollection class derives from the generic List class, and introduces methods to more easily manage multiple GamePiece objects.

Creating the Code

The constructor of the GamePieceCollection class initializes the private member capturedIndex. This field is used to track which of the game pieces currently has the mouse capture.

#region PrivateMembersAndConstructor
private int capturedIndex;

public GamePieceCollection()
{
    // No capture yet.
    capturedIndex = -1;
}
#endregion

The ProcessInertia and the Draw methods simplify the code needed in the game Game.Update and Game.Draw methods by enumerating all of the game pieces in the collection and calling the respective method on each GamePiece object.

#region ProcessInertiaAndDraw
public void ProcessInertia()
{
    foreach (GamePiece piece in this)
    {
        piece.ProcessInertia();
    }
}

public void Draw()
{
    foreach (GamePiece piece in this)
    {
        piece.Draw();
    }
}
#endregion

The UpdateFromMouse method is also called during game update. It enables only one game piece to have the mouse capture by first checking to see if the current capture (if any) is still in effect. If so, no other piece is allowed to check for capture.

If no piece currently has the capture, the UpdateFromMouse method enumerates each game piece from last to first, and checks to see if that piece reports a mouse capture. If so, that piece becomes the current captured piece, and no further processing takes place. The UpdateFromMouse method checks the last item in the collection first so that if two pieces are overlapped, the one with the higher Z-order will obtain the capture. Z-order is not explicit nor changeable; it is governed simply by the order in which game pieces are added to the collection.

#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

See Also

Concepts

Using Manipulations and Inertia in an XNA Application

Creating the GamePiece Class

Creating the Game1 Class

Full Code Listings

Other Resources

Manipulations and Inertia