XNA GameStudio 2.0
Keeping Score

In order to keep score we need to store the number of 'goals' that each player scores. To keep things simple, we will add two fields to the list we already have in the Game1.cs class.

int score1 = 0;
int score2 = 0;

Keeping Score

It was in the Update() method that we wrote code to detect a 'goal'. Find this section and replace the lines of code that you have with the following,

if (ball.position.X < 0)
   gamestate = 1;
   score2 += 1;
   ball.position = new Vector2(400.0f - ball.sprite.Width / 2, 300.0f - ball.sprite.Height / 2);
if (ball.position.X > 800.0f)
   gamestate = 2;
   score1 += 1;
   ball.position = new Vector2(400.0f - ball.sprite.Width / 2, 300.0f - ball.sprite.Height / 2);

Displaying The Score On The Screen

There isn't any point in keeping track of the score if we aren't going to do anything with the information. The most obvious thing that we need to do is to show the score on the screen for the players. We will draw this last so that the ball goes behind the score.

The first job is to specify a font to use. Go to the Solution Explorer window and click with the right mouse button on the Content folder.

XNA Screenshot

Select to add a new item and choose SpriteFont in the dialog box.

XNA Screenshot

A new code window pops up. This is an XML file that will contain the details of the font you use. The values you need to change are already there. Start by changing the following parts of the file to the values shown,


You can come back and change these values later to get the effect that you want.

Now we return to the code window. The first thing is to add a field to store a reference in the code to the font that we want to use.

SpriteFont gamefont;

Add the following line to the LoadContent() method.

gamefont = Content.Load<SpriteFont>("GameFont");

Finally, add the following lines to the Draw() method of the main game class.

spriteBatch.DrawString(gamefont, "Player 1: " + System.Convert.ToString(score1), new Vector2(30.0f, 10.0f), Color.White);
spriteBatch.DrawString(gamefont, "Player 2: " + System.Convert.ToString(score2), new Vector2(580.0f, 10.0f), Color.White);

Test out this stuff. We've just about made a game, don't you think?