Click here to Skip to main content
Click here to Skip to main content

Invasion Game in XNA for Windows Phone 7

By , 6 Jan 2012
 
Invasion Gameplay Screen Level 15

Introduction

Invasion is a UFO-shooter game, originally designed by Mauricio Ritter. This article describes my port of the Invasion game for Windows (in C# and Managed-DirectX) to Windows Phone 7 (C# and XNA 4.0). The full source code is provided.

Please remember to rate this article at the bottom of the page and if you install the XAP from the Marketplace, please rate & review it there too - Thanks!

Background

Back in 2002, Mauricio Ritter posted his "Invasion" UFO-shooter 2D game on CodeProject. It was written in C++ and used the DirectDraw APIs in DirectX 7 that Microsoft removed in DirectX 8. The following year, Steve Maier ported the game to C# with Managed DirectX and also posted it here on CodeProject. Managed DirectX went away after 2005 and was replaced by XNA. Both of those legacy versions ran on Windows XP. This article describes my 2011 week-long port of Steve's Managed DirectX version to Windows Phone 7 using XNA 4.0.

The articles mentioned above can be found here on CodeProject:

Using the Code

Invasion (v1.1) builds using the Windows Phone 7.1 SDK for Windows Phone 7.0 and 7.5 (Mango) operating systems. Note that Invasion v1.0 built against a pre-Beta version of the Windows Phone 7 SDK and that code will not build against the RTW WP7.1 SDK.

While XNA can currently be used to make Windows, Xbox 360, and Windows Phone games, this code will currently only work on Windows Phone 7. That limitation is a result of the implemented touch-screen and accelerometer inputs that replaced the mouse and keyboard inputs. To port this back to Windows, the input handlers and screen setup would need to be rewritten.

You can download the XAP file above and use the Application Deployment tool (from the Windows Phone Developer Tools) to install it on your phone, but to get XAP updates automatically, you would need to download and install the free game from the Windows Phone Marketplace.

Restructuring the Code

I had some goals for porting this game beyond "just get it working on Windows Phone 7". Specifically, they were:

  • Redesign the code into more manageable classes
  • Make the code more readable so that beginners could understand it
  • Simplify the code by using more C# language features and XNA framework classes
  • Polish the game so that I could release it on the Windows Phone Marketplace
  • Keep it free and Open-Source
  • But still finish the port within a week!

Considering my timeframe (which I extended by a few days), I was only somewhat successful. When I submitted v1.0 to the Marketplace, it was a "work-in-progress", and with v1.1, it still is!

The original code had only four source files: Invasion.cs, Ufo.cs, Extra.cs, and Bullet.cs. Ufo.cs defined a UFO class, Extra.cs defined a class for bonuses that the player will acquire, Bullet.cs defined a class for lasers and photon torpedoes, and Invasion.cs contained a class for everything else (which was way too much stuff!). In redesigning the game, I broke down Invasion.cs into multiple classes contained in these files:

  • InvasionGame.cs - The main game class for setting up the graphics device, content manager, sprite batch and 2D camera, screen manager, sound effects, music, app-level events, and scoreboard.
  • Invasion.cs - Still too big and complicated and should be further broken down into a screen-manager and game-screen subclasses.
  • ContentLoader.cs - Intended to use this to load all game content at startup, but currently only using it to load sound effects (it might go away in the next version).
  • Scoreboard.cs - A class to manage and display the scoreboard. This replaces the "status bar" from previous game versions and includes some new data items, controls, and features.
  • StarShip.cs - A class to represent our starship in the game. If aliens can have their own class, our hero should have one too!
  • TextHandler.cs - A class to manage the alpha.png bitmap font. I've updated the code here and added some characters to the font. Still, if you're using bitmap fonts, you'll find a better way to implement them in the "2D Graphics" (XNA for Windows Phone) sample at create.msdn.com.
  • BulletsManager.cs - A class to manage the collection of "bullets" (lasers and photons that have been fired).
  • ExtrasManager.cs - A class to manage the bonus items which are dropped by UFOs when they have been destroyed.
  • UFOsManager.cs - A class to manage all of the UFOs that are currently on-screen.

Borrowed Open Source Code

There were some features that I wanted to add to the game and fortunately had some already-made code files that made adding them quick and easy. You can find these files in the ImproviSoft namespace's Diagnostics, Drawing, and System projects. Don't let the namespace fool you though, this code is free Open-Source and my company (ImproviSoft) didn't write much of it. The files contain comments with their source indicated - primarily Microsoft's XNA team, XNAWiki.com, and Elbert Perez of OccasionalGamer.com. So thank them for it! Here's a list of those files:

  • FrameRateCounter.cs - displays the frames/second onscreen for debugging purposes, from Shawn Hargreaves (Microsoft XNA team).
  • SimpleShapes.cs - class for drawing 2D primitives (e.g., a Rectangle), from XNAWiki.com (although probably named something else there).
  • Accelerometer.cs - class for handling accelerometer input, from create.msdn.com (Microsoft XNA team).
  • Camera2D.cs - class for handling a 2D camera (to make the screen shake!), from Elbert Perez of OccasionalGamer.com - thanks, Elbert!
  • InputState.cs - class for handling all sorts of input devices, including the touch-screen, from create.msdn.com (Microsoft XNA team).
  • MusicManager.cs - class for playing background music, from create.msdn.com (Microsoft XNA team).
  • RandomManager.cs - simple class for generating random numbers - OK, I possibly wrote this and it took just two minutes.
  • SoundManager.cs - simple class to wrap SoundEffect.Play calls for sounds with adjusted maximum-volume.
  • VibrationManager.cs - class for making the phone vibrate on command (for force-feedback effect), from create.msdn.com (Microsoft XNA team).

The old version of the game did not have music in it, only sound effects. In adding the MusicManager.cs class, I found that Microsoft's sample code also contained a Music.mp3 file, which is also included in the Visual Studio solution's InvasionContent project. It loops repeatedly and if you get tired of it, feel free to turn off the music from the Options screen or replace it with your own music since you have the source code!

Code Changes Since the Managed DirectX Version

While Steve's port to Managed DirectX in C# was a straight port of the original C++ DirectX codebase, I didn't want to be bound by the design, data-structures, or variable names in this XNA port. So you'll find that there isn't a good one-to-one mapping back to the original source. I moved code all around to break out new classes, changed names of nearly all functions and variables (including the UFO class), and went to town on changing and adding data-types and function parameters. For this reason, I don't recommend trying to decipher what I changed in the code unless you are just interested in seeing how much of it has changed. I now have a wonderful new appreciation for right-click - Refactor - Rename. I also did my best to comment the important stuff in InvasionGame.cs so that an XNA beginner should be able to follow it, and I commented a few other classes too.

Screen Size and the Scoreboard

The earlier Windows versions of Invasion used a 640x480 window-size and placed the scoreboard at the bottom of the window. Because Windows Phone's screen is 800x480, I decided to move the scoreboard to the right (or left) side of the screen and free up the 20 vertical pixels at the bottom for gameplay use. Doing this kept the gameplay part of the screen at 640x480, which was ideal because many of the UFO sprites have hard-coded screen positions in their movement algorithms that I did not want to change (and mess up). It was also needed because with a phone screen measuring 4" diagonal, the scoreboard text needed to be resized for readability reasons. I chose the free Neuropol font for the new scoreboard's text. This is what the scoreboard looks like on each side of the screen. As you can see, the text in the selected weapon display still needs to be resized.

Invasion Gameplay Level 6

Invasion Gameplay Level 5

I also had to change the layout of the Main menu screen for the 800x480 screen resolution and in order to become more "touch-friendly". This is what it looks like now:

Invasion_v1.1_MainMenu.png

New Game Screens and Touch Controls

In porting to Windows Phone, I wanted the ability to pause the game and adjust some basic settings. Microsoft's game requirements specify how the hardware Back button must behave, so while pressing back at the Main menu should end the game, pressing it during gameplay should open a Pause screen. The Pause screen should provide a way for the user to resume the game in progress (by pressing Back again) and also provide a way for the user to exit the game app. The Pause screen implemented does just that and allows the user the ability to abandon the game and return to the Main menu screen. I updated the Main menu screen to include navigating to an Options screen where the user can adjust the scoreboard position, music on/off, difficulty level (something that was missing in the original Invasion game), and automatic-weapon-selection (AWS - another new feature!). This Options menu screen can also be opened during gameplay by pressing and holding the upper part of the scoreboard (perhaps not a great UI idea of mine - it really should have a button). Toggling AWS can also be done by tapping the AWS icon to the left of the selected weapon display. Tapping the selected weapon will change it to the next weapon if one is available. Because all of the inputs and controls were new, I updated the Help screen:

Invasion_v1.0_Help.png

Future Updates!

While there were many things that I wanted to get into this release, some things got cut in the interest of time. But of course, there is always the next release or the one after that. Here's a short list of what I'd like to add, and if you're interested in helping out, please contact me.

  1. Break down the Invasion.cs code into a ScreenManager and separate screen classes
  2. Save the user's preferences (game settings)
  3. Save and Resume the game, and Tombstoning
  4. Better shape-based collision detection - currently using rectangles for everything
  5. Re-render sprites at higher resolution and without clipping issues (is this a possibility, Mauricio?)
  6. More UFO types and UFO maneuvers or UFO Artificial Intelligence
  7. Local/Global high scores
  8. Allow switching scoreboard position during gameplay
  9. Replace "holding the scoreboard in order to open the Options screen" with something more obvious
  10. Use the create.msdn.com SpriteSheet code for the GameplayScreen textures
  11. Allow starship to get all the way to the left and right edges of the screen
  12. Allow starship ability to move up and down as well as left and right
  13. Make the laser's bounding box narrower

If you have any other ideas for improvements, please add them to the comments below!

Points of Interest

Color Key Transparency in XNA 4.0

Because all of the graphics already existed for this game, I really didn't want to recreate them. The sprite renders are a little grainy and somewhat awkwardly cropped, but they still look pretty darn good! But because they were originally rendered years ago as BMP files, and bitmap image files don't have an alpha channel, they used color-key transparency. While Steve had converted the sprite images to PNG format, which does have an alpha channel, they retained the black backgrounds so I had to use color-key transparency anyway. In DirectX (Managed DirectX too), color-keys are set for each texture (graphics image) in code, but in Visual Studio 2010 and XNA 4.0, color-keys are set in the graphic file's Properties. By default, XNA uses Magenta as a color key, but I wanted to remove the black sprite backgrounds, so I needed to change it. In Visual Studio 2010, click a PNG file in the Solution Explorer to see its properties. Click the little triangle to the left of "Content Processor" and set the "Color Key Color" field to the RGBA color that you want to make transparent. To change it to opaque-black, the color-key must be changed to [ 0, 0, 0, 255 ].

Pinning the Game to the Start Screen without a Tile Title

If you build this project, deploy it to your phone, and try to pin the game tile to your Start screen, you'll see "Default Title" awkwardly emblazoned across the bottom of the tile. This is because the Tile Title has been removed from the Invasion project's XNA Game Studio Properties. This isn't what I really want - I want it to be invisible, so I tried putting a space character in it to resolve the "Default Title" issue. When you do this, you unpin the tile from your Start screen (if it's there), and then open up the XNA Game Studio Properties page. Put a single space character in the Tile Title textbox and immediately build the game. The resulting XAP file will appear to have a blank Tile Title, but Visual Studio automatically removes the whitespace character from that textbox. So if you build again without reinserting the space character, you get "Default Title" again. So if you want a blank Tile Title on the Start screen, you must put the whitespace character in the textbox right before your final build. If anyone out there knows how to clear the Tile Title permanently, please let me know.

History

  • June 30, 2011 - The v1.0 release that I have also published on the Windows Phone Marketplace (as a free game without ads!)
  • July 2, 2011 - Article clarifications and fixed typos
  • July 10, 2011 - Added additional hyperlinks and replaced the "Comments and Renaming Variables" section title
  • December 10, 2011 - v1.1: Updated for Mango SDK, improved scoring, broke levels into waves and sectors, and made the game faster at 30fps
  • January 3, 2012 - Corrected the article regarding which version of the Windows Phone SDK to build the code with. No code changes.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Dan Colasanti
President ImproviSoft LLC
United States United States
Member
Dan is the Founder and President of ImproviSoft LLC, a Microsoft BizSpark Startup mobile software business.
 
Dan holds a B.S. in Computer Science from Clarkson University and M.S. degrees in Computer Science and Computer Engineering from Syracuse University. Dan is also an ASQ Certified Software Quality Engineer (CSQE) and a Microsoft XNA/DirectX MVP.
 
Dan writes articles about Windows Phone software development and other topics of interest on The ImproviSoft Blog.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionWIth VS2012, can't remove "default tile" with a space-charactermemberDan Colasanti25 Feb '13 - 17:07 
One of my lessons-learned for this article was how to remove the "default tile" text from showing up when the project doesn't specify a tile "title" and the game tile is then pinned to the Windows Phone start screen. With VS2010, this was achieved by putting a space-character in the title property field right before building the xap. VS2010 then removed the space character from the title right after doing the build, so "default tile" didn't show up. In VS2012, Microsoft changed the behavior, and putting a whitespace character for the title no longer shows a blank tile label when the tile's pinned to the start screen - it again says "default tile". Grrrr!!! Well, my new workaround for this is to put an ALT-255 character for the title instead - and it works just fine (or at least until Microsoft blocks ALT-255 in VS2014!) In case you don't know, to create an ALT-255 character:
 
(1) open Notepad
(2) Hold down the ALT key while typing 255 and then release the ALT key
(3) Select and copy (CTRL-C) the invisible character that you just created
(4) and paste (CTRL-V) it into your project Properties "XNA Game Studio" tab's Tile Title field.
 
Do a build and install the xap to your device. Then pin it to the start screen to verify that the tile title is blank. Note that Visual Studio 2012 ironically deletes the ALT-255 character after the build, just like VS2010 did with the space character, so you will need to do this right before your final build.
GeneralMy vote of 5memberPhat (Phillip) H. VU3 Jan '13 - 14:57 
Excellent
GeneralMy vote of 5mvpKanasz Robert21 Sep '12 - 1:28 
Nice. 5
GeneralMy vote of 5memberkhoa_chung_893 Aug '12 - 23:29 
a great article. I have found a lot of good things about XNA and Windows Phone from this project. Thanks a lot.
QuestionSpecial thanksmembertbgox16 Jun '12 - 8:13 
Hi Dan,
 
I came across this project and was inspired to create my own game with the XNA framework. Some of the ideas from Invasion helped me creating my WP7 game which I will be released on the Marketplace soon. With your permission I would like to add a special thanks note to you in my game.
 
Thanks!
AnswerRe: Special thanksmemberDan Colasanti16 Jun '12 - 10:08 
Hi tbgox,
 
That's great news about your game - I can't wait to see it on the Marketplace!
Thank you for the note too...
 
Best of Luck!
Dan
GeneralMy vote of 5memberPatrick Kalkman15 Jun '12 - 21:48 
Thanks for sharing, great article!
GeneralMy vote of 5memberEspen Harlinn6 Jan '12 - 3:35 
Excellent Smile | :)
Questionwell done. You got 5 [modified]memberrcastrogo15 Dec '11 - 23:03 
I like it
 
Try my first WP7 Game. And review please Smile | :)
 
Glypy the Hero
 
Glypy the Hero' Blog.
 
RcastroBlog

modified 16 Dec '11 - 5:22.

AnswerRe: well done. You got 5memberDan Colasanti16 Dec '11 - 2:49 
Your Glypy the Hero game looks great - Congratulations!
QuestionWow! Great sample and FUN!memberabdurahman ibn hattab14 Dec '11 - 15:39 
So my vote of 6 Poke tongue | ;-P
AnswerRe: Wow! Great sample and FUN!memberDan Colasanti16 Dec '11 - 2:50 
Thanks & Good luck!
Dan
QuestionWP7.5 Mango Update Coming Soon!memberDan Colasanti9 Dec '11 - 6:04 
I will be updating this game for WP7.5 Mango within the next week and will resubmit the Mango version to the Windows Phone Marketplace at that time. These are the only things I'm planning to change for this new version (v1.1):
 
(1) Upgrade to the WP7 Mango SDK
(2) More clearly map Levels to Waves and Sectors (6 sectors in each wave), so Level 3 is (Wave 1, Sector 3) and Level 7 is (Wave 2, Sector 1).
(3) Increase the scoring per hit and destroyed UFO by a factor of 10 (instead of 1 pt per hit and 10 pts per UFO destroyed, it's now 10 and 100 respectively (in wave #1)).
(4) Change the scoring method to account for Waves: so now instead of 10 points per UFO destroyed, the player will get (100 * Wave) points per UFO destroyed, and likewise for other scoring events.
(5) Increase the frame rate from 24fps to 30fps.
 
If you would like to propose any changes for the next version of Invasion, please post them here!
 
Thanks,
Dan
AnswerRe: WP7.5 Mango Update Coming Soon!memberDan Colasanti9 Dec '11 - 21:44 
Just submitted the updated article and code to CodeProject. Should be online within a few days...
GeneralRe: WP7.5 Mango Update Coming Soon!memberDan Colasanti11 Dec '11 - 4:13 
The article's been updated with new code & screenshots - enjoy!
 
Dan
GeneralRe: WP7.5 Mango Update Coming Soon!memberDan Colasanti26 Dec '11 - 20:05 
Just submitted the XAP to the Marketplace today... hopefully it will be approved within the next few days.
QuestionThanks for sharing.memberValentine_Kiev17 Nov '11 - 13:53 
How do you turn frameCounter on? I can't seem to understand.
AnswerRe: Thanks for sharing.memberDan Colasanti17 Nov '11 - 14:00 
You're welcome!
 
To show the FrameRateCounter: In InvasionGame.cs, make sure that none of the following lines are commented:
 
#if DEBUG
            frameRateCounter = new FrameRateCounter(this, spriteBatch);  //DEBUG Uncomment this line for debugging purposes only
            if (frameRateCounter != null) {
                frameRateCounter.DrawOrder = int.MaxValue;
                Components.Add(frameRateCounter);
            }
#endif
 
This will show the FrameRateCounter when running in Debug. If you are running in Release and would like to see the FrameRateCounter, then you should comment the #if and #endif lines.
 
You don't actually need to call the FrameRateCounter's Update and Draw functions in your code because the XNA framework will call Update and Draw automatically - because the frameRateCounter object was added to the Game object's Components list.
 
Good luck!
Dan
QuestionRe: Thanks for sharing.memberValentine_Kiev18 Nov '11 - 9:43 
Those lines weren't commented and I'm running game in debug mode. Counter doesn't appear though.
To make counter show up I suppose base.Draw(gameTime) method shoud be called, not sure...
 
InvansionGame.cs
protected override void Draw(GameTime gameTime) {
    GraphicsDevice.Clear(Color.Black);
 
    // Set up the SpriteBatch with the 2DCamera Transform
    spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, null, null, null, null, Camera2D.Instance.Transform);
 
    screenManager.Draw(gameTime);
    
    spriteBatch.End();
}

GeneralMy vote of 5memberYasser Azeem3 Aug '11 - 5:56 
Good job.
GeneralRe: My vote of 5memberDan Colasanti26 Dec '11 - 20:02 
Thank you!
GeneralMy vote of 5memberSteve Maier1 Jul '11 - 8:34 
Even if you did what I was going to do, I'll still give you a 5.
GeneralRe: My vote of 5memberDan Colasanti1 Jul '11 - 8:59 
Just think of all the time I saved you - Thanks for the 5 stars! Smile | :)
GeneralFYImemberThesisus11 Jul '11 - 16:09 
Dan, it looks great but only your first image is showing up the rest are broke.
Fear not my insanity, fear the mind it protects.

GeneralRe: FYImemberDan Colasanti11 Jul '11 - 16:25 
Thanks for the info - I'm seeing all images except for the 3rd one. Not sure why this is suddenly happening. I'll look into it.
GeneralRe: FYImemberDan Colasanti11 Jul '11 - 16:27 
... and after refreshing a couple times they are all appearing again - do you see them now?
GeneralRe: FYImemberThesisus11 Jul '11 - 16:32 
very odd... it seems random. I usually get at least the first but not always. Never all of them but usually at least two will show up. The first and last seem to be the most consistent.
Fear not my insanity, fear the mind it protects.

GeneralRe: FYImemberDan Colasanti11 Jul '11 - 16:38 
maybe it's a bandwidth issue at the server. I found that if you have picture placeholders enabled in your browser, right-clicking and selecting "Show Picture" makes them appear too.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 6 Jan 2012
Article Copyright 2011 by Dan Colasanti
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid