Time for action - implementing score tracking

  1. Add a declaration to the Player class to store the player's score:
    private int score = 0;
    
  2. Add a property to the Player class to allow access to the score variable:
    public int Score
    {
    get { return score; }
    set { score = value; }
    }
    
  3. Replace the current Update() method in the LevelManager class with the following new version of the method:
    public static void Update(GameTime gameTime)
    {
    if (!player.Dead)
    {
    for (int x = gemstones.Count - 1; x >= 0; x--)
    {
    gemstones[x].Update(gameTime);
    if (player.CollisionRectangle.Intersects(
    gemstones[x].CollisionRectangle))
    {
    gemstones.RemoveAt(x);
    player.Score += 10;
    }
    }
    }
    }
    
  4. In the Game1 class, add a declaration for a SpriteFont instance that we can use to draw the player's score and a vector pointing to the location on the screen where the score will be displayed:
    SpriteFont pericles8;
    Vector2 scorePosition = new Vector2(20, 580);
    
  5. In the LoadContent() method of the Game1 class, initialize the pericles8 font:
    pericles8 = Content.Load<SpriteFont>(@"FontsPericles8");
    
  6. In the Draw() method of the Game1 class, add a call to display the current score right before the spriteBatch.End() call:
    spriteBatch.DrawString(
    pericles8,
    "Score: " + player.Score.ToString(),
    scorePosition,
    Color.White);
    
  7. Execute the Gemstone Hunter application and collect a few gemstones:
Time for action - implementing score tracking

What just happened?

When called, the LevelManager.Update() method checks each of the gemstones that exist for the current level and compares their CollisionRectangle properties to the same property of the player object. If these rectangles intersect, the gemstone is removed from the gemstones list and the player's score is incremented. Remember that we need to use a reverse-running for loop here because we can potentially modify the contents of the list, and a foreach loop will throw an exception if the list is modified during the loop.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.2.15