Game Development Reference
In-Depth Information
Finally, we need to draw the pairs on the screen, in the
Draw
method. Here, we
use a
for
-instruction to traverse all the indices in the pair list. For each index, we
draw the right sprite at the appropriate position. Note that we use the same sprite
and simply draw it multiple times, with different sheet indices:
public override void
Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
base
.Draw(gameTime, spriteBatch);
if
(!visible)
return
;
for
(
int
i=0; i<pairs.Length; i++)
{
∗
sprite.Height, 8);
pairSprite.Position =
new
Vector2(110 + i
pairSprite.Sprite.SheetIndex = pairs[i];
pairSprite.Draw(gameTime, spriteBatch);
}
}
The call to the base
Draw
method ensures that the background frame is drawn first.
Now that we have the
PairList
class, we can create an instance of it in the
Level
class and add it to the game world:
PairList pairList =
new
PairList(nrpairs, 1, "pairList");
pairList.Position =
new
Vector2(20, 15);
this
.Add(pairList);
And inside the
Animal
class, we add a pair to the list with the following two lines of
code:
PairList pairList = GameWorld.Find("pairList")
as
PairList;
pairList.AddPair(sprite.SheetIndex);
For the complete example, see the
PenguinPairs5
program in the solution belonging
to this chapter. In the next chapter, we will add the final touches to the
Penguin Pairs
game, and we will show you a better way to reuse code among different projects.
23.7 What You Have Learned
In this chapter, you have learned:
•
how to program a game object selector;
•
how to model interactions between different kinds of game objects;
•
how to maintain and draw the number of pairs made by the player.