Creating your 1st Game (5 of 5) – by Ben Coley, Academic Developer Evangelist

The time has come to complete our XNA Pacman game!  This time, we're adding the ability to store a high score.  To do this, we need a file to store it in - for this purpose, we can use a simple text file.  Seeing as the same .NET classes are used to store files, the code I've used will work on both Windows and the Xbox 360.

On to the code!  Firstly, I needed to add another global variable to keep track of the high score, as well as the score that we're already keeping track of.  So under the "int Score;" line, I've added "int HighScore;" too.

Next, we've got to read the current high score (if there is one!).  The way I did this, was to add some code to read a text file.  I added this code under the LoadContent() routine:


What this basically does is tries to read the text file into the HighScore variable, but if the file doesn't exist, it sets the variable as 0.

The next thing to do is to check to see if, when the game finishes, the current score is higher than the high score.  If it is, we need to overwrite the previous high score with the new one, before resetting the game.

If you remember from before, we added some code in the Draw() routine, that looked like "if (endGame) {...}".  Under the existing code in that block, I've added a bunch of new stuff to test the current score against the high score, and store it if it's better:


What this does is overwrites the high score, if it has been beaten.  It will also create a "score.txt" file if one doesn't already exist.  The exception catching is there just in case something goes wrong; then the high score is set to 0 again.

Finally, we need to draw the current high score on the screen and to do that, I used an adapted version of the code used to draw the current score:


And that's it!  Now we have a fully-functional, playable game!  The next challenge might be to implement a menu, or port the game to the Xbox 360!  But hopefully this has given you a good idea of how to start building basic games for Windows and the Xbox 360, using XNA.

Skip to main content