Home > Articles > Programming > C#

Building Breakernoid in MonoGame, Part 4

This is the fourth and final article on how to create a clone of classic brick-breaking games using C# and MonoGame. In this part, Sanjay Madhav (author of Game Programming Algorithms and Techniques) shows you how to add levels that load from XML, scoring, lives, and improved ball bouncing.
Like this article? We recommend

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:


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:

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020