Building Breakernoid in MonoGame, Part 4
- Levels / Scoring and Lives
- Polishing the Paddle Bouncing / Where to Go from Here
This is the fourth and final article in a series in which you build a clone of classic brick-breaking games called Breakernoid.
At the end of the third article, you had a pretty functional game. However, having only one level isn't very exciting, so in this article you're going to add more levels. You'll also add scoring and lives to complete the game.
Catch up on the other articles in this series:
Levels
For the level file format, you're going to use XML. Although XML is definitely not the most compact way to store this level data, it has two advantages: it is plain text, so it can be easily edited; and C# has built-in functionality to save and load classes to an XML file (called serialization).
In order to load the levels, you first need to make a new Level class in a separate Level.cs file. In order for the serialization to work properly, you must use the following exact class declaration—if your Level doesn't match this declaration, the serialization will not work:
public class Level { public int[][] layout; public float ballSpeed; public string nextLevel; }
Note that you didn't use a multidimensional array like int[,], but instead you used a jagged array int[][]. That's because the XML serializer doesn't support multidimensional arrays, but it does support jagged arrays.
This means the memory layout is different, but accessing an element in a jagged array isn't that different: you use [i][j] instead of [i,j].
All the level files you will use are in Breakernoid_levels.zip. In Visual Studio, you'll want to create a new folder in the project called Levels, and then use "Add Existing Item" to add all the Level*.xml files into this folder.
You'll also need to right-click these files and select "Properties" to change the "Copy to Output Directory" setting to "Copy if Newer."
In Xamarin Studio on Mac, you'll have to right-click the files and select "Build Action>Content."
Next, you should remove the blockLayout member variable because you won't be using it any more. For now, comment out the code in LoadContent that loads in the blocks from blockLayout. You'll be replacing it with some other code in a second.
Now add a member variable to Game1 of type Level that's called level, which is where you'll store the level data that's read in from the XML files.
You then need to add two using statements to the top of Game1.cs for System.IO and System.Xml.Serialization. Add a LoadLevel function to Game1.cs that takes a string specifying the level file to load in.
Because the syntax for the XmlSerializer is a little odd, here is the skeleton code for the LoadLevel function:
protected void LoadLevel(string levelName) { using (FileStream fs = File.OpenRead("Levels/" + levelName)) { XmlSerializer serializer = new XmlSerializer(typeof(Level)); level = (Level)serializer.Deserialize(fs); } // TODO: Generate blocks based on level.layout array }
After you load the level, you need to loop through the level.layout jagged array and generate the blocks as appropriate. This will be very similar to what you did before, except you use [i][j] and level.layout.Length to get the number of rows and level.layout[i].Length to get the number of columns.
In fact, you can just copy the code you commented out before that loaded blocks from blockLayout and use it with some minor modifications.
There's one other change to watch out for: some indices have a 9 stored in them, which won't convert to a block color. This is a special value that means you should skip over that particular index because it is empty.
After this LoadLevel function is implemented, go ahead and call LoadLevel from LoadContent, and pass in "Level5.xml" for the file name.
Try running the game now. If you get a file loading error, this might mean that you didn't put the level files into the Levels directory correctly.
If you were successful, you should see a block layout, as shown in the following figure:
Notice that the Level class also has a ballSpeed parameter. Every time you spawn a ball, you should set its speed to ballSpeed. This way, the later levels can increase the speed over the previous levels.
Because there are only five levels right now, level 5 will wrap around back to level 1. So you should also add a speed multiplier that's initialized to 0 and increased by 1 every time you beat level 5.
Then add 100 * speedMult to the ball speed, which ensures that the speed will continue to increase as the player gets further and further into the game.
The last variable in the Level class is the nextLevel, which stores the name of the next level that should be loaded once the current level is finished.
So make a new function in Game1 called NextLevel, which you'll call when there are zero blocks left in the blocks list.
In NextLevel, make sure you turn off all power-ups, clear out all the balls/power-ups in the respective lists, reset the position of the paddle, and spawn a new ball. Then call LoadLevel on the next level.
As for where you should check whether there are no blocks left, I suggest doing so at the end of the Game1.Update function.
To test this next level code, change it so you first load in "Level1.xml" and beat the level to see whether the second level loads.
Scoring and Lives
The last major piece that will help the game feel complete is to add scoring and lives and then display them with text onscreen. You'll also have text that pops up at the start of the level and specifies the level number you're in.
For the score, you just need to add a new score int in Game1 that you initialize to zero.
The rules for scoring are pretty simple:
- Every block the player destroys gives 100 + 100 * speedMult points.
- Every power-up the player gets gives 500 + 500 * speedMult points.
- When the player completes a level, they get a bonus of 5000 + 5000 * speedMult + 500 * (balls.Count - 1) * speedMult.
Notice that all the scoring equations are a function of speedMult, so if players keep completing the levels over and over, the number of points they get increases. There's also a bonus to the level completion based on the number of balls the player has up on level completion.
In any event, make sure you create an AddScore function that you call when you want to change the score instead of directly modifying the score. This way, you can have one centralized location to do checks for things such as awarding an extra life.
After you have a score, it's time to display it onscreen. To do this, you first need to add a SpriteFont member variable to Game1.
You can then load this font in LoadContent, like so:
font = Content.Load("main_font");
In Game1.Draw, you can then draw the score text using code like this:
spriteBatch.DrawString(font, String.Format("Score: {0:#,###0}", score), new Vector2(40, 50), Color.White);
This code formats the score with commas for numbers greater than 999. The font you're using is "Press Start 2P" from http://openfontlibrary.org/, which is a great retro gaming font that's free to use.
Before you add in lives, you will add code that gives a bit of a reprieve between levels. When loading a new level, rather than spawning the ball immediately, you will display text that says what level the player is in for 2 seconds. After 2 seconds, you'll hide that text and spawn the ball.
To support this, you need to add two member variables: a bool that specifies whether you're in a level break and a float that tracks how much time is left in the break.
Then you should change the Game1.Update function so that nothing in the world is updated while the level break is active. Instead, during the break, all you should do is subtract delta time from the float tracking the remaining time for the break.
Once that float becomes <= 0, you can then set the break bool to false and spawn the ball.
You now want to make a function called StartLevelBreak, which sets the level break bool to true and the remaining time to 2.0f.
In LoadContent and NextLevel, call StartLevelBreak instead of SpawnBall. If you do all this, when you start the game there should now be a 2-second delay before the gameplay begins.
Now add text that specifies what level you're in. This means you need to add a levelNumber variable that you initialize to 1 and increment every time you go to the next level.
Next, in Game1.Draw, if you are in a level break, you can draw text specifying the level number. Ideally, you want this text to be centered onscreen.
What you can do is query the font for the size of a string using MeasureString and use the length/width of this rectangle to determine where to draw the string.
The code will look something like this:
string levelText = String.Format("Level {0}", levelNumber); Vector2 strSize = font.MeasureString(levelText); Vector2 strLoc = new Vector2(1024 / 2, 768 / 2); strLoc.X -= strSize.X / 2; strLoc.Y -= strSize.Y / 2; spriteBatch.DrawString(font, levelText, strLoc, Color.White);
If you run the game now, you should notice that the name of the level is displayed during a 2-second break.
Now let's add lives. The player should start out with three lives, and every time LoseLife is called, they should lose one. If the player has zero lives left and dies, rather than spawning a new ball you should just display "Game Over."
You'll also want to display the number of lives left in the top-right corner of the screen, which will be very similar to displaying the score (except that you don't need commas).
Finally, you also want to give the player an extra life every 20,000 points. One way to do this is to have a counter that you initialize to 20000 and subtract from every time points are earned.
Then, when it becomes less than or equal to 0, you can reset the counter and add a life. You should also play the power-up SFX when the player gains an extra life.
You should now have a game that's pretty complete, and the score/level text displays should look like the following figure: