Windows Phone Resources
Last week, we added scoring, and keeping track of the high score over a set of games. The problem is, when you exit the game for any reason, you lose your high score. That’s because everything is unloaded from memory, so when you start your game over, it has nothing to start from. This week, we’ll save your high score to a file, so we can load it back up when you restart your game. To begin, we’ll load the code from last week over at the SkyDrive Share.
When working with files, we’ll need to add a few libraries. On the Windows Phone, applications have access to a special type of storage called IsolatedStorage, which is a file store that is accessible only by your application. Additionally, we will be storing our high score in an XML format, and accessing it with LINQ. To work with these, we’ll the following three include statements:
Once we’ve got these, we’ll just need to set up two simple methods. We simply need to save to the file, and load from the file. We’ll then just need to update the game to call the load method when it starts, and the save method at the end of each game.
At the beginning of the SaveToFile method, we choose a file name to save the game state. You then open the Isolated Storage and open a file stream into it. We use FileMode.Create because we just want to overwrite a file if it’s there, and make a new one if it isn’t. The StreamWriter lets us write directly into the file we created in Isolated Storage. We then create a basic XML file that contains the high score inside of a State element.
To load from the file, we use the same file name we defined when we saved our state. We then open the Isolated Storage using a StreamReader, and load its contents into a XDocument. This lets us use LINQ to pull in the elements that we saved. We walk through the elements named HighScore, and parse its contents into the highScore variable. The whole thing is wrapped in a try catch block because the file might not be there, or maybe there is something wrong with the file. We don’t want that to crash the game, so we just let it go.
Now we need to use these methods. First of all, we just need to load in the file in the Initalize method.
And finally, we need to save it. You could put it in every time the high score is beaten, but file I/O is expensive, so this could cause performance problems. Since we are really storing game high scores, why not drop it into the update method when the player dies.
And there you go, your high score is saved across application launches. Remember that if you restart the emulator, your isolated storage will be blown away, so you’ll lose your high score. This will also happen in you uninstall the game and then redeploy.
Next week, we’ll be adding sound effects, so stay tuned.
Download the latest version of the source code.
Time to add scoring! To add a competitive edge to the game, let’s add in a running total of how many enemies you’ve shot. We’ll also keep track of the high score across games so you can try to beat your last score. To do this, we’ll make use of a Sprite Font. A Sprite Font is a font specially prepared by taking a set of characters and converting them to textures. So let’s get started. To begin, we’ll want to grab the code from last week over at the SkyDrive share.
The first thing that we’ll want to do is create a new Sprite Font. Right-click on the TriangleShooterContent project, and choose Sprite Font. Under name, type “Font.spritefont”, and then click Add. It will open in the editor, in all it’s XML glory. As you can see by looking at the file, it describes a specific version of a font. You define the Font’s name, size, spacing, whether to use kerning or not, the style, a default character, and the portion of the font to include. The document is well commented, and is easy enough to understand. The one thing that might catch you up is the CharacterRegions. Because games require a lot of efficiency, you want to minimize any overhead possible. This includes characters from a font you wouldn’t use. This is especially important when you want to use non-Latin characters, such as Chinese or Japanese, because they won’t be included in the default Character Region. If you’re going to be using a lot of non-Latin characters, I suggest you take a look at the Localization Sample on AppHub.
We’ll change two things. First, change the FontName field to Kootenay. Second, change the Size field to 32. This will give us a readable font for the phone.
Next, we’ll need to set up our variables. We’ll be counting the number of enemies you shoot, so well use an integer named score, and an integer named highScore to keep track of the record. We’ll also need a variable to hold our font.
We’ll initialize the highScore in the Initialize method
And the score in the NewGame method.
Then load up the font in the LoadContent method
Now we’re ready to start keeping score. Inside of the Update method, where we do the collision for bullets, we add a few lines to a successful collision. We increment the score, then check if the score is greater than the high score. If that’s the case, we update the high score to equal the current score. All together, the updated bullet collision detection part of the Update method looks like the following
Finally, we add a couple of lines to the Draw method. We use the spriteBatch.DrawString method. The High score is left aligned, so we just tell it to draw at Vector2.Zero, the top left position. For the Score, we want to right align, which means we have to set the offset based on the width of the string. To do this, we use the font.MeasureString function, and subtract it from the width of the Viewport. The lines look like this:
With those changes, we now have scoring, and the updated game looks like this:
When you die, the score resets, but the high score remains. If you reset the game, though, you��ll lose your high score. That’s why next week we’ll be looking at persistent storage, and save the high score to a file we can load when the game starts.
This time around, we’ll be doing a bit of refactoring to make the code easier to deal with, and adding in some death behavior. To begin with, we’ll need to start with the code from last week, so go ahead and pick that up from the SkyDrive share.
To begin with, let’s update the Initialize and LoadContent methods, and move some of the setup into a new method called NewGame. This will allow us to reset the game back to it’s initial state more easily, such as when you get killed by running into an enemy.
If we update the collision detection, we can call NewGame now if the collision happens, which means we can reset the game with ease. Also, while I was setting this up, I found a bug in the code based around the origin of the drawing and the rectangle we were using for collision. The updated code in the Update method looks like the following:
Now, when you die, the game resets. It might make more sense to freeze the game, and wait for the player to choose to continue before resetting the game. To do that, let’s create a new variable to say whether the player is alive or not. Let’s call it isPlayerDead
And initialize it to false in the NewGame method
Then check if the player is dead in the Update method
This means that the Collision detection from above needs to be updated once more to set the boolean rather than calling NewGame directly.
And we’ve now got a game that actually ends when you die, and let’s you start a new game. Sounds like we’re ready for scoring. We’ll add that in next week. See you then.
Let’s make TriangleShooter a better game. This time around, we’ll be putting the shooter in TriangleShooter, by adding in the ability for the player to shoot. We’ll be starting with last week’s code, so you can go over and grab that from my SkyDrive share.
I tried a few different ways of making the player shoot in my development of the game, and the best one I have found so far is to have you always laying out a steady stream of shots. Towards the end of the series, I’ll be doing some play mechanics tweaking, and we can investigate some of the other ways, but that’s how I’m going to do things in this article.
If you’re going to shoot, you need a bullet. You can get my highly stylized, square bullet from the SkyDrive share. To begin with, download that, then add it into the TriangleShooterContent project by dragging it and dropping it in there. We’ll also need a class to handle the bullet, which is going to look familiar. Create a new class in the TriangleShooter project named Bullet.cs, and set the content to the following:
We’ll set up the variables at the top of the game class to hold the texture, the list of Bullets, and to monitor the passing time to shoot, along with a constant to tweak the timer a bit.
In the Initialize method, we set up the list for the bullets, and set the time to shoot from the constant value we set up.
And add some code into the LoadContent method to load in the texture.
And now we’ve got everything we need. We only have the Update and Draw to go. The Update is more interesting, so let’s start there.
The first part of the code is similar to what we do to spawn enemies. We subtract the elapsed time from the remaining time, and if the time is less than zero, we spawn a new bullet, setting it’s position to the front of the player and the rotation to the players rotation. We then update all existing bullets. Because we may need to remove them from the master list, we make a copy in the foreach by using the .ToList() function. We move them in the direction based on their rotation, and see if they have left the bounds of the screen. If they have, we remove them from the update list. To optimize things here, we should do something like create a list of decommissioned bullets, and reuse them rather than creating new ones each time, but we won’t do that this time around. If they are within the bounds of the screen, we check collision with each of the enemies, again using the .ToList() function because we might need to remove items. If they collide, we remove both the bullet, and the enemy that collided with it.
This is all we need to do, but we do need to draw the bullets. Luckily, this is a simple process, just add a few lines into Draw.
And now we have shooting!
Next week, we’ll do some refactoring to make the code easier to work with, and see if we can add in some death behavior.
Time for my favorite part of Monday – Another article improving my TriangleShooter game! Last week, I promised you that I would spawn some more enemies, and that I would add in some other enemy types to make it more visually appealing. The great news is, both of those things are pretty easy. We’ll get started with the code base from last week, so you can grab that from my SkyDrive share.
We can start by adding in some additional enemy types. To begin with, we’ll drag and drop the rest of the Enemies from the Enemies file from SkyDrive into the Content project with the first enemy. We’ll then create some variables to hold the textures.
We’ll then load them from the content project in the LoadContent method.
We can try this out by changing the lines further down in LoadContent to make use of the new textures.
Next up, we need to start spawning some more enemies. What we’re looking to do here is to bring in new enemies every so often. The faster you spawn the enemies, the more difficult the game would be, so you can play with the amount of time between spawns. In order to track them, though, we’ll need a variable to track how long we have left until the next spawn. Since we’ve got some different enemy types, we may as well add in some randomization, so we’ll create a variable to handle randomness as well. As always, we’ll drop the variable up at the top of the game file.
And then we initialize them down in Initalize()
This sets up timeToSpawn as one second. We’ll count down until this reaches zero, then spawn another enemy. Luckily, there’s a easy way to get elapsed game time in the Update Method with the gameTime argument. We’ll subtract the elapsed game time from the timeToSpawn variable, then check to see if it is less than or equal to zero. If it is, we create a new enemy and add it to the enemies list. To add variety, we can pick a random edge, and spawn the enemy somewhere along it so that it doesn’t just always come from the same spot. Finally, we’ll reset the timeToSpawn so that we can spawn another. All of this will go in the Update method after we check the enemy collision.
There’s just so many of them!
Next week, we’ll add in shooting! Until this point, we were just a triangle moving around, but now we’ll finally be a triangle that shoots!