Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web...

62
Hands-On Lab Game Development with XNA Framework Lab version: 2.0.0 Last updated: 4/2/2022 Page | 1 ©2011 Microsoft Corporation. All rights reserved.

Transcript of Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web...

Page 1: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

Hands-On LabGame Development with XNA FrameworkLab version: 2.0.0

Last updated: 5/18/2023

Page | 1

©2011 Microsoft Corporation. All rights reserved.

Page 2: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

CONTENTS

OVERVIEW................................................................................................................................................. 3

EXERCISE 1: XNA GAME STUDIO GAMES ON THE WINDOWS PHONE 7...........................................5Task 1 – XNA Game Studio Game Basics..............................................................................................7

Task 2 – XNA Framework Game Resources.........................................................................................9

Task 3 – XNA Game Studio Game Loop..............................................................................................21

Task 4 – Game Specific Logic.............................................................................................................28

Task 5 – Lifetime event handling.......................................................................................................46

SUMMARY................................................................................................................................................ 54

Page | 2

©2011 Microsoft Corporation. All rights reserved.

Page 3: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

Overview

This lab introduces you to XNA Game Studio game development on Windows Phones, as well as to the basics of XNA Game Studio game development. During the lab you will build a simple XNA Game Studio game application that introduces key concepts in XNA Game Studio game development and learn how to use Microsoft Visual 2010 Express for Windows Phone to build and design your XNA Game Studio games for Windows Phones.

Objectives

At the end of the lab you will have:

A high-level understanding of the XNA Game Studio game engine model within a Windows Phone 7 application

Learned how to use resources (images, fonts, etc.) in your XNA Game Studio game

Learned how to add game logic

Learned about the drawing mechanism for Windows Phone XNA Game Studio games

Prerequisites

The following is required in order to complete this hands-on lab:

Microsoft Visual Studio 2010 Express for Windows Phone or Microsoft Visual Studio 2010

Windows Phone Developer Tools

Note: To download the tools, go to http://go.microsoft.com/?linkid=9772716. This lab assumes use of the Windows Phone 7.1 SDK.

Tasks

This hands-on lab includes the following tasks:

1. XNA Game Studio Game Basics

2. XNA Framework Resources

3. XNA Game Studio Game Loop

4. XNA Game Studio Game Input

5. Alien Game Specific LogicPage | 3

©2011 Microsoft Corporation. All rights reserved.

Page 4: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

Estimated time to complete this lab: 60 minutes.

Page | 4

©2011 Microsoft Corporation. All rights reserved.

Page 5: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

Exercise 1: XNA Game Studio Games on the Windows Phone 7

If you have ever wanted to make your own games, Microsoft® XNA™ Game Studio 4.0 is for you. Student, hobbyist, independent game developer — anybody can create and share great games using XNA Game Studio.XNA Game Studio 4.0 is a game development product from Microsoft that is built on top of the Microsoft Visual Studio 2010 Express for Windows Phone, giving game developers the power and simplicity of C# as a programming language. XNA Game Studio 4.0 includes the XNA Framework and the XNA Framework Content Pipeline, which provide an easy and flexible way to import three-dimensional (3D) models, textures, sounds, and other assets into your game, and a game-focused application-programming interface (API) that simplifies development for Xbox 360®, Windows® and now Windows Phone 7®.

The XNA Framework is an application-programming interface (API). What that means is that it is a framework developed by Microsoft to help you make games faster. However, it's not a drag and drop game maker and you will need to learn how to program before you can use it. It is easy to use, but you will have to be somewhat technical to develop games with it.

The XNA Framework is not a game engine. It does not include physics, collision detection, or other things often found in game engines. It is a game development framework, but how the game works is programmed entirely by you.

During this lab you will build a full XNA Game Studio game for the Windows Phone – “Alien Game” – a simple shooter game. The goal in Alien Game is simple: Protect earth against the invading aliens for as long as possible. The longer you last, the more difficult the game becomes. Watch out for the smaller aliens that come out at night!

General Architecture

Alien Game uses the game screen management architecture from the Game State Management sample (found at http://create.msdn.com/en-US/education/catalog/sample/game_state_management), which provides the assets for this lab. The game includes three possible states:

Main menu (MainMenuScreen class)

Playing the game (GameplayScreen class)

Paused (PauseScreen class)

Alien Game performs all content loading at startup. The first thing it does is to load and display the BackgroundScreen (which serves to display a background for both the main menu and pause screens, but does not represent a state). Next, it loads and displays the LoadingScreen, which loads the rest of the game’s content asynchronously. The LoadingScreen could display some form of progress, but the

Page | 5

©2011 Microsoft Corporation. All rights reserved.

Page 6: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

loading times are so short in this sample that displaying progress would be pointless. Once all of the content is loaded, the MainMenuScreen is loaded and displayed, and the menus animate onto the screen. This allows for quicker transitions between the main menu and game play, without a lengthy pause as the content is loaded. This helps the hard-drive-based devices especially, as the hard drive may spin down.

GameplayScreen and Game Classes

The design and implementation of Alien Game is relatively simple. All logic and drawing is contained in the GameplayHelper class. The file containing the gameplay helper, GameplayHelper.cs, contains some additional classes that represent the game’s entities, namely Bullet, Alien, and Player. The gameplay screen employs the gameplay helper to present the user with the actual game.

ParticleSystem

Alien Game includes a simple sprite-based particle system that displays explosion and dust effects.

The completed game will look as follows:

Figure 1Alien Game running on Windows Phone

XNA Game Studio Game Basics

A game typically consists of multiple levels. Levels are connected to each other by the game plot, game player, enemies, etc. Each level can be treated as a complete, small, game.

A level usually has three states:

Page | 6

©2011 Microsoft Corporation. All rights reserved.

Page 7: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

Loading – In this state, the system loads resources, sets up level-related variables, calculates the game-world (game-world is the place where all the game process occurs), and performs any other tasks that must be performed before the game actually begins. This state occurs only once in the level/game life cycle.

Update – In this state, the system needs to update the game-world state. Usually this means calculating new positions for the various game entities (player(s) and enemies), updating health, ammo, and other states and recalculating the score and other game logic according to the game. This state occurs throughout the time that the game engine is active.

Draw – In this state, the system draws the changes calculated in the update state to the output graphics device. This state occurs throughout the time that the game engine is active.

In the XNA Framework, the last two stages can occur up to 60 times per second on a PC or Xbox 360 and up to 30 times per second on a Zune, Zune HD or Windows Phone 7 device.

Task 1 – XNA Game Studio Game Basics

In this section, you will create your first XNA Game Studio game for the Windows Phone. The game will be a simple one, but you will add functionality throughout the lab.

Note: The steps in this hands-on lab illustrate procedures using Microsoft Visual Studio 2010 Express for Windows Phone, but they are equally applicable to Microsoft Visual Studio 2010 with the Windows Phone Developer Tools. Instructions that refer generically to Visual Studio apply to both products.

1. Open Microsoft Visual Studio 2010 Express for Windows Phone from Start | All Programs | Microsoft Visual Studio 2010 Express | Microsoft Visual Studio 2010 Express for Windows Phone.

Note: Visual Studio 2010: Open Visual Studio 2010 from Start | All Programs | Microsoft Visual Studio 2010.

2. In the File menu, choose New Project.

3. In the New Project dialog, select the XNA Game Studio 4.0 for Windows Phone category and, from the list of installed templates, select Windows Phone Game (4.0). Call the new project AlienGame. When the target phone framework dialog appears, choose “Windows Phone 7.1”.

4. In Solution Explorer, review the structure of the solution generated by the Windows Phone Application template. Any Visual Studio solution is a container for related projects; in this case, it contains an XNA Game Studio game for Windows Phone project named AlienGame and a related games resources project named AlienGameContent.

Page | 7

©2011 Microsoft Corporation. All rights reserved.

Page 8: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

5. Add a reference to the newly created AlienGame project for the Microsoft.Phone assembly.

6. The generated project includes a default game implementation that contains the basic XNA Game Studio game loop. It is located in the Game1.cs file.

7. Open the Game1.cs file. We recommend that you change the default name to the name that reflects your game.

8. Rename the main game class (default name Game1) to AlienGame.

9. Rename the filename to match the new class name. Right-click on Game1.cs in Solution Explorer and choose Rename. Give the class the new name AlienGame.cs.

10. Press F5 to launch the application in the Windows Phone Emulator. Notice that a device emulator window appears and there is a pause while Visual Studio sets up the emulator environment and deploys the image. Once it is ready, the emulator shows the Start page and shortly thereafter, your application appears in the emulator window.

The application will display a simple blue screen with nothing else shown. This is normal to an application in such early stages.

Figure 2Running the application in the Windows Phone Emulator

Page | 8

©2011 Microsoft Corporation. All rights reserved.

Page 9: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

Until you create the user interface and program the application logic, there is very little that you can do with the application.

11. Press SHIFT + F5 or click the Stop button in the toolbar to detach the debugger and end the debugging session. Do not close the emulator window.

Task 2 – XNA Framework Game Resources

Many games using pre-defined images to present the game, process sound, etc. This lab provides you with a number of such resources to make the game development process easier. During this task, you will add those resources to the game. This lab also provides a number of code files to handle the complexity of menu and screen changes during the game. You will add those files to the game also.

Note: All the game resources are provided in the lab install folder under the following locations:

Source\Assets\Code – all CSharp code files

Source\Assets\Media – all graphics, fonts and sounds

1. Close the project in Visual Studio. Switch to Windows Explorer, navigate to the project location and copy two files from the Source\Assets\Media\Images\Icons folder of this lab into the “AlienGame” directory, replacing the existing files:

◦ Game.ico

◦ PhoneGameThumb.png

2. Re-open Visual Studio 2010 and open the AlienGame project.

Most games use art in the form of models, meshes, sprites, textures, effects, terrains, animations, and so on. Such art assets can be created in many different ways and stored in many different file formats. They tend to change frequently in the course of game development. The Content Pipeline is designed to help you include such art assets in your game easily and automatically. An artist working on a car model can add the resulting file to the XNA Game Studio game project, assign the model a name, and choose an importer and content processor for it. Then, a developer who wants to make the car drive can load it by name using a call to ContentManager.Load. This simple flow lets the artist focus on creating assets and the developer focus on using them, without either having to spend time worrying about content transformation.

The XNA Content Pipeline is readily integrated into your XNA Game Studio project. You just add the resource to your project and when you compile it, the data is imported and converted in a XNB (XNA Binary File) using a Content Importer. This XNB file is generated for the right platform.

Page | 9

©2011 Microsoft Corporation. All rights reserved.

Page 10: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

Content Importers are implemented as assemblies. In addition to the standard ones provided by XNA Game Studio, you can also use custom importers and processors that you or other third parties develop. Some of standard Content Importers include the following file types (partial list):

◦ Autodesk FBX format (.fbx)

◦ DirectX Effect file format (.fx)

◦ Font description specified in a .spritefont file

◦ Texture file. The following types are supported: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga

◦ Game audio specified in the Microsoft Cross-Platform Audio Creation Tool (XACT) format (.xap)

3. This lab provides a number of media resources such as fonts, sounds, and images. Add the following items to the AlienGameContent project:

◦ All the fonts from the Source\Assets\Media\Fonts folder

◦ All the images from the Source\Assets\Media\Images\Content folder

◦ All the sounds from the Source\Assets\Media\Sounds folder

4. Add a new project folder under the AlienGame project and name it ScreenManager.

This folder will hold source files provide by the lab, which will help to manage the complexity of creating game screens, menus, and of navigating between them.

Note: This code implements the standard approach for creating XNA Game Studio menus and screens and may be found at the following link: http://create.msdn.com/en-US/education/catalog/sample/game_state_management.

5. Add all existing Screen Manager files from the Source\Assets\Code\ScreenManager folder of this lab to the project folder created in the previous step.

6. Add the ParticleSystem.cs file from the Source\Assets\Code folder to the root of the AlienGame project.

7. Add a reference to the System.Windows assembly.

8. Add a new class to the AlienGame project and name it BackgroundScreen:

9. Open the new class and add the following using directives:

C#

using AlienGameSample;using Microsoft.Xna.Framework.Graphics;using Microsoft.Xna.Framework;

Page | 10

©2011 Microsoft Corporation. All rights reserved.

Page 11: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

10. Derive the new class from the GameScreen class (the GameScreen class is defined in classes added previously to the ScreenManager folder):

C#

class BackgroundScreen : GameScreen{}

11. Add the following class variables to be used later for loading resources:

C#

Texture2D title;Texture2D background;

12. Define a class constructor as follows:

C#

public BackgroundScreen(){ TransitionOnTime = TimeSpan.FromSeconds(0.0); TransitionOffTime = TimeSpan.FromSeconds(0.5);}

13. The GameScreen Class defines some core game functionality according to what was described in the exercise preface: LoadContent, Update, and Draw. Override the base class’s LoadContent functionality:

C#

public override void LoadContent(){ title = ScreenManager.Game.Content.Load<Texture2D>("title"); background = ScreenManager.Game.Content.Load<Texture2D>("background");}

This code loads content from the game’s resources. You can see that we load two pieces of content by name.

14. Now create a LoadingScreen class. The screen supported by the class will be presented while game resources are being loaded.

15. Add following using directives to the LoadingScreen class:

C#

Page | 11

©2011 Microsoft Corporation. All rights reserved.

Page 12: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

using AlienGameSample;using System.Threading;using Microsoft.Xna.Framework;using Microsoft.Phone.Shell;

16. Derive this new class from the GameScreen base class (like you did for the previous class), and add a constructor as follows:

C#

class LoadingScreen : GameScreen{ public LoadingScreen(bool showPauseScreen) { TransitionOnTime = TimeSpan.FromSeconds(0.0); TransitionOffTime = TimeSpan.FromSeconds(0.0);

this.showPauseScreen = showPauseScreen; }}

17. Add a couple of fields. One to hold the thread which will be used to load the components and another to determine the type of screen that shows up after all content has been loaded:

C#

private Thread backgroundThread;private bool showPauseScreen;

18. Create a method to load the content. This approach is part of the standard loading procedures in XNA programming. We will defer the actual loading to the gameplay helper class, which we will create later in this task:

C#

void BackgroundLoadContent(){ GameplayHelper gameplayHelper;

// If we have never created a gameplay helper yet, now is the time. Otherwise, we simply need to reload its content, possibly. if (PhoneApplicationService.Current.State.ContainsKey(AlienGame.GameStateKey)) {

Page | 12

©2011 Microsoft Corporation. All rights reserved.

Page 13: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

gameplayHelper = PhoneApplicationService.Current.State[AlienGame.GameStateKey] as GameplayHelper; } else { gameplayHelper = new GameplayHelper(ScreenManager.Game.Content, ScreenManager.SpriteBatch, ScreenManager.Game.GraphicsDevice);

PhoneApplicationService.Current.State[AlienGame.GameStateKey] = gameplayHelper; }

if ((ScreenManager.Game as AlienGame).ReloadRequired) { gameplayHelper.InitializeAssets(ScreenManager.Game.Content, ScreenManager.SpriteBatch, ScreenManager.Game.GraphicsDevice);

gameplayHelper.LoadContent();

(ScreenManager.Game as AlienGame).GameplayHelper = gameplayHelper; } }

The above code is not as straightforward as simply creating a gameplay helper and using it to load content, so let us review it. Our eventual goal is to have the gameplay helper class not only facilitate the game’s logic and drawing, but also serve as a representation of the game’s current state. To that end, the gameplay helper will be serializable, allowing us to preserve its state once our game is deactivated. The code above examines the game’s persistable state dictionary for an existing gameplay helper or creates a new one and places it in said dictionary. Then, if an asset reaload is necessary, the gameplay helper is instructed to load the game’s assets and is then stored in an additional location for easy access.

Note: To properly understand the code above, you should be familiar with application lifecycle management on the Windows Phone 7. See the following link: http://msdn.microsoft.com/en-us/library/ff817008%28VS.92%29.aspx.

19. Override the base class’s LoadContent method and initiate the content loading as a new thread to achieve asynchronous loading of the resources:

Note: In our simple game, the resources will be loaded almost instantaneously, but when dealing with games that are more complex, this approach allows showing a progress indicator or a splash screen.

C#

Page | 13

©2011 Microsoft Corporation. All rights reserved.

Page 14: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

public override void LoadContent(){ if (backgroundThread == null) { backgroundThread = new Thread(BackgroundLoadContent); backgroundThread.Start(); }

base.LoadContent();}

20. Override the base class’s Update method to wait for content loading to finish and then proceed to either the main menu or pause screens (added in the next steps):

C#

public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen){ if (backgroundThread != null && backgroundThread.Join(10)) { backgroundThread = null; this.ExitScreen();

if (showPauseScreen) { // TODO: Add pause screen } else { ScreenManager.AddScreen(new MainMenuScreen()); }

ScreenManager.Game.ResetElapsedTime(); }

base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);}

You can see that we’ve placed a placeholder where will later add the pause screen.

21. Let us introduce the GameplayHelper class used in the loading screen. Create a new class with that name in the AlienGame project. Be sure to mark the class as public.

22. Add a reference to the AlienGame project for the System.Xml.Serialization assembly.

23. Add the following using directives to the new class’s file, which should be called GameplayHelper.cs (we will require all of them eventually):

C#Page | 14

©2011 Microsoft Corporation. All rights reserved.

Page 15: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

using Microsoft.Xna.Framework.Graphics;using Microsoft.Xna.Framework;using Microsoft.Xna.Framework.Audio;using Microsoft.Xna.Framework.Content;using System.IO.IsolatedStorage;using System.IO;using Microsoft.Xna.Framework.Input.Touch;using System.Xml.Serialization;using System.Xml;using System.Xml.Schema;

24. Add the following fields to the GameplayHelper class:

C#SoundEffect alienFired;SoundEffect alienDied;SoundEffect playerFired;SoundEffect playerDied;

Texture2D cloud1Texture;Texture2D cloud2Texture;Texture2D sunTexture;Texture2D moonTexture;Texture2D groundTexture;Texture2D tankTexture;Texture2D alienTexture;Texture2D badguy_blue;Texture2D badguy_red;Texture2D badguy_green;Texture2D badguy_orange;Texture2D mountainsTexture;Texture2D hillsTexture;Texture2D bulletTexture;Texture2D laserTexture;

SpriteFont scoreFont;SpriteFont menuFont;

ContentManager contentManager;SpriteBatch spriteBatch;GraphicsDevice graphicsDevice;

The gameplay helper will use the bottom three fields in the code above for content loading and rendering. The other fields will be used to store loaded content.

25. Change the GameplayHelper class to implement IXmlSerializable. Add the following placeholder methods which we will flesh out later in the lab:

C#

public XmlSchema GetSchema(){

Page | 15

©2011 Microsoft Corporation. All rights reserved.

Page 16: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

return null;}

public void ReadXml(XmlReader reader){ // TODO: Deserialize the gameplay state}

public void WriteXml(XmlWriter writer){ // TODO: Serialize the gameplay state}

26. Add the following constructor for the class:

C#

public GameplayHelper(ContentManager contentManager, SpriteBatch spriteBatch, GraphicsDevice graphicsDevice){ // TODO: Perform additional initializations

InitializeAssets(contentManager, spriteBatch, graphicsDevice);}

27. Add the InitializeAssets helper method seen above:

C#

public void InitializeAssets(ContentManager contentManager, SpriteBatch spriteBatch, GraphicsDevice graphicsDevice){ this.contentManager = contentManager; this.spriteBatch = spriteBatch; this.graphicsDevice = graphicsDevice;

// TODO: Perform additional initializations}

28. Add the LoadContent method used in previous steps for loading content:

C#

public void LoadContent(){ cloud1Texture = contentManager.Load<Texture2D>("cloud1"); cloud2Texture = contentManager.Load<Texture2D>("cloud2"); sunTexture = contentManager.Load<Texture2D>("sun"); moonTexture = contentManager.Load<Texture2D>("moon"); groundTexture = contentManager.Load<Texture2D>("ground"); tankTexture = contentManager.Load<Texture2D>("tank");

Page | 16

©2011 Microsoft Corporation. All rights reserved.

Page 17: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

mountainsTexture = contentManager.Load<Texture2D>("mountains_blurred"); hillsTexture = contentManager.Load<Texture2D>("hills"); alienTexture = contentManager.Load<Texture2D>("alien1"); badguy_blue = contentManager.Load<Texture2D>("badguy_blue"); badguy_red = contentManager.Load<Texture2D>("badguy_red"); badguy_green = contentManager.Load<Texture2D>("badguy_green"); badguy_orange = contentManager.Load<Texture2D>("badguy_orange"); bulletTexture = contentManager.Load<Texture2D>("bullet"); laserTexture = contentManager.Load<Texture2D>("laser"); alienFired = contentManager.Load<SoundEffect>("Tank_Fire"); alienDied = contentManager.Load<SoundEffect>("Alien_Hit"); playerFired = contentManager.Load<SoundEffect>("Tank_Fire"); playerDied = contentManager.Load<SoundEffect>("Player_Hit"); scoreFont = contentManager.Load<SpriteFont>("ScoreFont"); menuFont = contentManager.Load<SpriteFont>("MenuFont");

// TODO: Load the highscores}

29. Add an additional class definition to the GameplayHelper.cs file as follows:

C#

public class Player{ public Vector2 Position; public Vector2 Velocity; public float Width; public float Height; public bool IsAlive; public float FireTimer; public float RespawnTimer; public string Name; public int Score; public int Lives;}

30. Now add a new class (in a new file) and name it MainMenuScreen. When created, add the following using statements to it:

C#

using AlienGameSample;using Microsoft.Phone.Shell;

31. Derive the new class from the MenuScreen base class. This class is also defined in classes added to the ScreenManager folder and facilitates all typical functionality needed to show/interact with menus and menu items.

32. Create the MainMenuScreen class constructor:

Page | 17

©2011 Microsoft Corporation. All rights reserved.

Page 18: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

C#

class MainMenuScreen : MenuScreen{ public MainMenuScreen() : base("Main") { // Create our menu entries. MenuEntry startGameMenuEntry = new MenuEntry("START GAME"); MenuEntry exitMenuEntry = new MenuEntry("QUIT");

// Hook up menu event handlers. startGameMenuEntry.Selected += StartGameMenuEntrySelected; exitMenuEntry.Selected += OnCancel;

// Add entries to the menu. MenuEntries.Add(startGameMenuEntry); MenuEntries.Add(exitMenuEntry); }}

33. In the above constructor, we subscribed to two events, which will fire when the user selects menu items. Create the event handler methods to handle those events:

C#

void StartGameMenuEntrySelected(object sender, EventArgs e){ // TODO: Move to the actual game}

protected override void OnCancel(){ ScreenManager.Game.Exit();}

34. Open the AlienGame.cs file and add the following using statement:

C#

using AlienGameSample;using Microsoft.Phone.Shell;using System.IO.IsolatedStorage;

35. Delete the entire contents of the AlienGame class.

36. Add the following class members to the AlienGame class:

C#

Page | 18

©2011 Microsoft Corporation. All rights reserved.

Page 19: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

public const string GameStateKey = "GameState";public const string InGameKey = "InGame";

/// <summary>/// Whether or not asset reloading is required./// </summary>public bool ReloadRequired { get; set; }

/// <summary>/// Allows storing the game's gameplay helper./// </summary>public GameplayHelper GameplayHelper { get; set; }

GraphicsDeviceManager graphics;ScreenManager screenManager;

37. Add the following constructor to the AlienGame class:

C#

public AlienGame(){ graphics = new GraphicsDeviceManager(this);

//Set the Windows Phone screen resolution graphics.PreferredBackBufferWidth = 480; graphics.PreferredBackBufferHeight = 800;

Content.RootDirectory = "Content";

// Hook up lifecycle events PhoneApplicationService.Current.Launching += Game_Launching; PhoneApplicationService.Current.Activated += Game_Activated; PhoneApplicationService.Current.Closing += Game_Closing;

// Frame rate is 30 fps by default for Windows Phone. TargetElapsedTime = TimeSpan.FromSeconds(1 / 30.0);

//Create a new instance of the Screen Manager screenManager = new ScreenManager(this); Components.Add(screenManager); }

The above constructor initializes the screen manager and registers to some of the game’s lifecycle events.

38. Add the handlers for the various lifecycle events:

C#

private void Game_Closing(object sender, ClosingEventArgs e)Page | 19

©2011 Microsoft Corporation. All rights reserved.

Page 20: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

{ // TODO: Perform cleanup}

private void Game_Activated(object sender, ActivatedEventArgs e){ // TODO: Handle reactivation}

private void Game_Launching(object sender, LaunchingEventArgs e){ ReloadRequired = true;

PhoneApplicationService.Current.State[InGameKey] = false;

// Display the main screen screenManager.AddScreen(new BackgroundScreen()); screenManager.AddScreen(new LoadingScreen(false));}

39. Compile and run the application. After the application loads, the main menu screen should appear:

Page | 20

©2011 Microsoft Corporation. All rights reserved.

Page 21: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

Figure 3The game’s main menu

40. Stop the debugging and return to editing the application.

During this task, you added resources to the game and created a number of screens to present the user with some basic user interfaces while loading the game. You also created the main menu.

Task 3 – XNA Game Studio Game Loop

In this task, you will focus on having the various game screens update and draw properly.

1. Open BackgroundScreen.cs.

2. Override the base class Update method as follows:

C#

public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen){ base.Update(gameTime, otherScreenHasFocus, false);}

3. Override the base class Draw method. The Draw method will use the SpriteBatch class from the Microsoft.Xna.Framewok.Graphics namespace to draw on the graphics device. It enables a group of sprites to be drawn using the same settings. Define a Draw method matching the following code:

C#

public override void Draw(GameTime gameTime){ SpriteBatch spriteBatch = ScreenManager.SpriteBatch;

spriteBatch.Begin();

// Draw Background spriteBatch.Draw(background, new Vector2(0, 0), new Color(255, 255, 255, TransitionAlpha));

// Draw Title spriteBatch.Draw(title, new Vector2(60, 55), new Color(255, 255, 255, TransitionAlpha));

spriteBatch.End();}

Page | 21

©2011 Microsoft Corporation. All rights reserved.

Page 22: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

4. Press F5 to compile and run the application.

Figure 4The game after having the background screen update and draw

5. Stop the debugging (SHIFT+F5) and return to editing the application. Our next goal is to create the gameplay screen and enhance the gameplay helper to support the fully functional game.

6. Add a reference in the AlienGame project to the Microsoft.Devices.Sensors assembly.

7. Add an additional class to the application and set its name to GameplayScreen.

8. Add the following using statements to the new class:

C#

using AlienGameSample;using Microsoft.Xna.Framework;using Microsoft.Xna.Framework.Graphics;using Microsoft.Xna.Framework.Audio;using Microsoft.Xna.Framework.Input;using Microsoft.Xna.Framework.Input.Touch;using Microsoft.Devices.Sensors;

Page | 22

©2011 Microsoft Corporation. All rights reserved.

Page 23: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

using Microsoft.Phone.Shell;

9. Derive the class from GameScreen.

C#

class GameplayScreen : GameScreen{}

10. Add following Field definitions:

C#

SensorReadingEventArgs<AccelerometerReading> accelState;Accelerometer Accelerometer;

GameplayHelper gameplayHelper;

11. Add the following constructor, which will initialize the handling of accelerometer input:

C#

public GameplayScreen(){ TransitionOnTime = TimeSpan.FromSeconds(0.0); TransitionOffTime = TimeSpan.FromSeconds(0.0);

Accelerometer = new Accelerometer(); if (Accelerometer.State == SensorState.Ready) { Accelerometer.CurrentValueChanged += (s, e) => { accelState = e; }; Accelerometer.Start(); }}

12. Override the base class’s LoadContent method to get the current gameplay helper and state that we are now in an active game:

C#

public override void LoadContent(){ gameplayHelper = PhoneApplicationService.Current.State[AlienGame.GameStateKey] as GameplayHelper;

PhoneApplicationService.Current.State[AlienGame.InGameKey] = true;

Page | 23

©2011 Microsoft Corporation. All rights reserved.

Page 24: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

base.LoadContent();}

13. Override the base class’s Draw and Update methods. These will simply call the corresponding methods on the gameplay helper (we will add these later on):

C#

public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen){ float elapsedSeconds = (float)gameTime.ElapsedGameTime.TotalSeconds;

if (IsActive) { gameplayHelper.Update(elapsedSeconds); }

base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);}

public override void Draw(GameTime gameTime){ float elapsedSeconds = (float)gameTime.ElapsedGameTime.TotalSeconds;

gameplayHelper.Draw(elapsedSeconds);}

14. Finally, add an override to HandleInput for feeding the accelerometer input to the gameplay helper:

C#

public override void HandleInput(InputState input){ Vector3 accelerationInfo = accelState == null ? Vector3.Zero : new Vector3((float)accelState.SensorReading.Acceleration.X, (float)accelState.SensorReading.Acceleration.Y, (float)accelState.SensorReading.Acceleration.Z);

if (gameplayHelper.HandleInput(input.PauseGame, accelerationInfo, TouchPanel.GetState())) { // TODO: Finish the current game } else if (input.PauseGame) { // TODO: Pause the current game }

Page | 24

©2011 Microsoft Corporation. All rights reserved.

Page 25: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

}

15. We are finished with the gameplay screen for the moment. Let us move on to updating the gameplay helper with some methods we used while constructing the gameplay screen. But first, let us add some additional fields to the gameplay helper for future use. Open GameplayHelper.cs and add the following field definitions to the GameplayHelper class:

C#

private const string SerializationNamespace = @"http://schemas.microsoft.com/2003/10/Serialization/Arrays";

Rectangle worldBounds;bool gameOver;int baseLevelKillCount;int levelKillCount;float alienSpawnTimer;float alienSpawnRate;float alienMaxAccuracy;float alienSpeedMin;float alienSpeedMax;int alienScore;int nextLife;int hitStreak;int highScore;Random random;

Vector2 cloud1Position;Vector2 cloud2Position;Vector2 sunPosition;

// Level changes, nighttime transitions, etcfloat transitionFactor; // 0.0f == day, 1.0f == nightfloat transitionRate; // > 0.0f == day to night

ParticleSystem particles;

// Screen dimension constantsconst float screenHeight = 800.0f;const float screenWidth = 480.0f;const int leftOffset = 25;const int topOffset = 50;const int bottomOffset = 20;

// Actor variablesPlayer player;List<Alien> aliens;List<Bullet> alienBullets;List<Bullet> playerBullets;

Page | 25

©2011 Microsoft Corporation. All rights reserved.

Page 26: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

16. At the very bottom of the above code block, you can see that we define some variables for storing the player, the aliens and their respective bullets. Still in the GameplayHelper.cs file, add the following class definitions:

C#

public class Bullet{ public Vector2 Position; public Vector2 Velocity; public bool IsAlive;}

public class Alien{ public Vector2 Position; [XmlIgnore] public Texture2D Texture; public string TextureName; public Vector2 Velocity; public float Width; public float Height; public int Score; public bool IsAlive; public float FireTimer; public float Accuracy; public int FireCount;}

17. Back in the GameplayHelper class, change the class’s constructor by replacing the “TODO” comment located inside it with the following code:

C#

random = new Random();

worldBounds = new Rectangle(0, 0, (int)screenWidth, (int)screenHeight);

gameOver = true;

player = new Player();playerBullets = new List<Bullet>();

aliens = new List<Alien>();alienBullets = new List<Bullet>();

particles = new ParticleSystem(contentManager, spriteBatch);

In the code above simply initialize some of the game’s entities and define the size of the “game world”, where all the game’s actions take place.

Page | 26

©2011 Microsoft Corporation. All rights reserved.

Page 27: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

18. Add the following placeholder methods that we will change later in the exercise.

C#

public void Update(float totalElapsedSeconds){ // TODO: Add game update logic}

public void Draw(float totalElapsedSeconds){ // TODO: Add game drawing logic}

public bool HandleInput(bool pauseGame, Vector3 acceleration, TouchCollection touchInfo){ // TODO: Add input handling logic

return false;}

public void Start(){ // TODO: Initialize the game's state and start it}

You will notice that the last method, Start, was not used when we created the gameplay screen. You will see it being used in the next step.

19. Open MainMenuScreen.cs, locate the StartGameMenuEntrySelected method, and replace the “TODO” comment inside it with the following code. This will add the GameplayScreen screen to the ScreenManager when user clicks “START GAME” button:

C#

(PhoneApplicationService.Current.State[AlienGame.GameStateKey] as GameplayHelper).Start();

ScreenManager.AddScreen(new GameplayScreen());

20. Compile and run the application. Click the “START GAME” menu entry and observe the main menu items scrolling down from the screen.

Page | 27

©2011 Microsoft Corporation. All rights reserved.

Page 28: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

Figure 5Trying to start the game

Note: The Gameplay screen is still empty, and so all you will see is the menu disappearing once you select “Start Game”.

21. Stop debugging and return to editing the application.

During this task, you created the foundations of the gameplay screen and the gameplay helper, which will handle the game’s logic.

Task 4 – Game Specific Logic

In this task, you will create game-specific logic. Therefore, the focus of this task will be the gameplay helper.

1. We will begin by adding some additional initializations to the gameplay helper. Open GameplayHelper.cs and move to the GameplayHelper class’s InitializeAssets method. Replace the “TODO” comment in the method with the following code:

C#

SetAlienTextures();

Page | 28

©2011 Microsoft Corporation. All rights reserved.

Page 29: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

particles.InitializeAssets(contentManager, spriteBatch);particles.SetParticleTextures();

The above code assigns the various alien objects their associated texture and performs some additional initializations for the particle system.

2. Add the SetAlienTextures method seen above using the following code:

C#

private void SetAlienTextures(){ foreach (Alien alien in aliens) { alien.Texture = contentManager.Load<Texture2D>(alien.TextureName); }}

3. Move to the Update method and replace the “TODO” comment inside the method with the following code:

C#

// Move the playerif (player.IsAlive == true){ player.Position += player.Velocity * 128.0f * totalElapsedSeconds; player.FireTimer -= totalElapsedSeconds;

if (player.Position.X <= 0.0f) player.Position = new Vector2(0.0f, player.Position.Y);

if (player.Position.X + player.Width >= worldBounds.Right) player.Position = new Vector2(worldBounds.Right - player.Width, player.Position.Y);}

Respawn(totalElapsedSeconds);

UpdateAliens(totalElapsedSeconds);

UpdateBullets(totalElapsedSeconds);

CheckHits();

if (player.IsAlive && player.Velocity.LengthSquared() > 0.0f) particles.CreatePlayerDust(player);

particles.Update(totalElapsedSeconds);

Page | 29

©2011 Microsoft Corporation. All rights reserved.

Page 30: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

You can see that the game’s update cycle is composed of moving the player according to the velocity derived from the accelerometer input (which we will handle later), handling the player’s respawning in case of death, updating the various bullets, checking for hits (the player hitting aliens and vice versa) and updating the game’s particles.

4. We will begin adding the various methods used during the update cycle. Use the following code to add the Respawn method:

C#

void Respawn(float elapsed){ if (gameOver) return;

if (!player.IsAlive) { player.RespawnTimer -= elapsed; if (player.RespawnTimer <= 0.0f) { // See if there are any bullets close... int left = worldBounds.Width / 2 - tankTexture.Width / 2 - 8; int right = worldBounds.Width / 2 + tankTexture.Width / 2 + 8;

for (int i = 0; i < alienBullets.Count; ++i) { if (alienBullets[i].IsAlive == false) continue;

if (alienBullets[i].Position.X >= left || alienBullets[i].Position.X <= right) return; }

player.IsAlive = true; player.Position = new Vector2(worldBounds.Width / 2 - player.Width / 2, worldBounds.Bottom - groundTexture.Height + 2 - player.Height); player.Velocity = Vector2.Zero; player.Lives--; } }}

This method deducts from the player’s life count after dying and resets his position once there are no enemy bullets nearby.

5. Add the UpdateAliens method using the following code:

Page | 30

©2011 Microsoft Corporation. All rights reserved.

Page 31: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

C#

private void UpdateAliens(float elapsed){ // See if it's time to spawn an alien; alienSpawnTimer -= elapsed; if (alienSpawnTimer <= 0.0f) { SpawnAlien(); alienSpawnTimer += alienSpawnRate; }

for (int i = 0; i < aliens.Count; ++i) { if (aliens[i].IsAlive == false) continue;

aliens[i].Position += aliens[i].Velocity * elapsed; if ((aliens[i].Position.X < -aliens[i].Width - 64 && aliens[i].Velocity.X < 0.0f) || (aliens[i].Position.X > worldBounds.Width + 64 && aliens[i].Velocity.X > 0.0f)) { aliens[i].IsAlive = false; continue; }

aliens[i].FireTimer -= elapsed;

if (aliens[i].FireTimer <= 0.0f && aliens[i].FireCount > 0) { if (player.IsAlive) { Bullet bullet = CreateAlienBullet(); bullet.Position.X = aliens[i].Position.X + aliens[i].Width / 2 - laserTexture.Width / 2; bullet.Position.Y = aliens[i].Position.Y + aliens[i].Height; if ((float)random.NextDouble() <= aliens[i].Accuracy) { bullet.Velocity = Vector2.Normalize(player.Position - aliens[i].Position) * 64.0f; } else { bullet.Velocity = new Vector2(-8.0f + 16.0f * (float)random.NextDouble(), 64.0f); }

Page | 31

©2011 Microsoft Corporation. All rights reserved.

Page 32: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

alienFired.Play(); }

aliens[i].FireCount--; } }}

The above code spawns aliens, moves them across the top of the screen, marking them as dead if they exit the game world. The code is also responsible for causing the aliens to fire bullets towards the player.

6. Add the CreateAlienBullet and SpawnAlien and methods used in the previous step’s code. We will also introduce an additional method called CreateAlien that we will use to initialize an alien object and place it in the proper list:

C#

Bullet CreateAlienBullet(){ Bullet b = null;

for (int i = 0; i < alienBullets.Count; ++i) { if (alienBullets[i].IsAlive == false) { b = alienBullets[i]; break; } }

if (b == null) { b = new Bullet(); alienBullets.Add(b); }

b.IsAlive = true;

return b;}

private void SpawnAlien(){ Alien newAlien = CreateAlien();

if (random.Next(2) == 1) { newAlien.Position.X = -64.0f;

Page | 32

©2011 Microsoft Corporation. All rights reserved.

Page 33: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

newAlien.Velocity.X = random.Next((int)alienSpeedMin, (int)alienSpeedMax); } else { newAlien.Position.X = worldBounds.Width + 32; newAlien.Velocity.X = -random.Next((int)alienSpeedMin, (int)alienSpeedMax); }

newAlien.Position.Y = 24.0f + 80.0f * (float)random.NextDouble();

// Aliens if (transitionFactor > 0.0f) { switch (random.Next(4)) { case 0: newAlien.Texture = badguy_blue; newAlien.TextureName = "badguy_blue"; break; case 1: newAlien.Texture = badguy_red; newAlien.TextureName = "badguy_red"; break; case 2: newAlien.Texture = badguy_green; newAlien.TextureName = "badguy_green"; break; case 3: newAlien.Texture = badguy_orange; newAlien.TextureName = "badguy_orange"; break; } } else { newAlien.Texture = alienTexture; newAlien.TextureName = "alien1"; }

newAlien.Width = newAlien.Texture.Width; newAlien.Height = newAlien.Texture.Height; newAlien.IsAlive = true; newAlien.Score = alienScore;

float duration = screenHeight / newAlien.Velocity.Length();

newAlien.FireTimer = duration * (float)random.NextDouble();Page | 33

©2011 Microsoft Corporation. All rights reserved.

Page 34: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

newAlien.FireCount = 1;

newAlien.Accuracy = alienMaxAccuracy;}

Alien CreateAlien(){ Alien b = null;

for (int i = 0; i < aliens.Count; ++i) { if (aliens[i].IsAlive == false) { b = aliens[i]; break; } }

if (b == null) { b = new Alien(); aliens.Add(b); }

b.IsAlive = true;

return b;}

The SpawnAlien method appears lengthy, yet it is a rather simple method which deals primarily with deciding what type of alien to create.

7. Add the UpdateBullets method, which takes care of moving bullets around based on their velocity and destroying them once they exit the game world:

C#

void UpdateBullets(float elapsed){ for (int i = 0; i < playerBullets.Count; ++i) { if (playerBullets[i].IsAlive == false) continue;

playerBullets[i].Position += playerBullets[i].Velocity * elapsed;

if (playerBullets[i].Position.Y < -32) { playerBullets[i].IsAlive = false;

Page | 34

©2011 Microsoft Corporation. All rights reserved.

Page 35: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

hitStreak = 0; } }

for (int i = 0; i < alienBullets.Count; ++i) { if (alienBullets[i].IsAlive == false) continue;

alienBullets[i].Position += alienBullets[i].Velocity * elapsed;

if (alienBullets[i].Position.Y > worldBounds.Height - groundTexture.Height - laserTexture.Height) alienBullets[i].IsAlive = false; }}

8. Add the CheckHits method. This is a fairly length method that handles all collision related logic such as increasing the player’s score once an alien is hit, advancing to the next level after a certain amount of aliens have been killed, causing the player to explode if hit by one of the aliens’ bullets and so on:

C#

void CheckHits(){ if (gameOver) return;

for (int i = 0; i < playerBullets.Count; ++i) { if (playerBullets[i].IsAlive == false) continue;

for (int a = 0; a < aliens.Count; ++a) { if (aliens[a].IsAlive == false) continue;

if ((playerBullets[i].Position.X >= aliens[a].Position.X && playerBullets[i].Position.X <= aliens[a].Position.X + aliens[a].Width) && (playerBullets[i].Position.Y >= aliens[a].Position.Y && playerBullets[i].Position.Y <= aliens[a].Position.Y + aliens[a].Height)) { playerBullets[i].IsAlive = false; aliens[a].IsAlive = false;

Page | 35

©2011 Microsoft Corporation. All rights reserved.

Page 36: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

hitStreak++;

player.Score += aliens[a].Score * (hitStreak / 5 + 1);

if (player.Score > highScore) highScore = player.Score;

if (player.Score > nextLife) { player.Lives++; nextLife += nextLife; }

levelKillCount--; if (levelKillCount <= 0) AdvanceLevel();

particles.CreateAlienExplosion(new Vector2(aliens[a].Position.X + aliens[a].Width / 2, aliens[a].Position.Y + aliens[a].Height / 2));

alienDied.Play(); } } }

if (player.IsAlive == false) return;

for (int i = 0; i < alienBullets.Count; ++i) { if (alienBullets[i].IsAlive == false) continue;

if ((alienBullets[i].Position.X >= player.Position.X + 2 && alienBullets[i].Position.X <= player.Position.X + player.Width - 2) && (alienBullets[i].Position.Y >= player.Position.Y + 2 && alienBullets[i].Position.Y <= player.Position.Y + player.Height)) { alienBullets[i].IsAlive = false;

player.IsAlive = false;

hitStreak = 0;

player.RespawnTimer = 3.0f; particles.CreatePlayerExplosion(new Vector2(player.Position.X + player.Width / 2, player.Position.Y + player.Height / 2));

Page | 36

©2011 Microsoft Corporation. All rights reserved.

Page 37: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

playerDied.Play();

if (player.Lives <= 0) { gameOver = true; } } }}

9. Add an additional helper method called AdvanceLevel for advancing to the next game level:

C#

void AdvanceLevel(){ baseLevelKillCount += 5; levelKillCount = baseLevelKillCount; alienScore += 25; alienSpawnRate -= 0.3f; alienMaxAccuracy += 0.1f; if (alienMaxAccuracy > 0.75f) alienMaxAccuracy = 0.75f;

alienSpeedMin *= 1.35f; alienSpeedMax *= 1.35f;

if (alienSpawnRate < 0.33f) alienSpawnRate = 0.33f;

if (transitionFactor == 1.0f) { transitionRate = -0.5f; } else { transitionRate = 0.5f; }}

10. Finally, add an additional method named CreatePlayerBullet, which we will use later, for creating bullets fired by the player:

C#

Bullet CreatePlayerBullet(){ Bullet b = null;

for (int i = 0; i < playerBullets.Count; ++i)

Page | 37

©2011 Microsoft Corporation. All rights reserved.

Page 38: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

{ if (playerBullets[i].IsAlive == false) { b = playerBullets[i]; break; } }

if (b == null) { b = new Bullet(); playerBullets.Add(b); }

b.IsAlive = true;

return b;}

11. We have implemented the game’s logic and can move on to the game’s presentation. Replace the “TODO” comment in the GameplayHelper’s Draw method with the following code:

C#

spriteBatch.Begin();

DrawBackground(totalElapsedSeconds);DrawAliens();DrawPlayer();DrawBullets();particles.Draw();DrawForeground(totalElapsedSeconds);DrawHud();

spriteBatch.End();

The above code is essentially a list of all the various elements that we must draw to display the game.

Note: Following is a short description of each of the drawing helper methods we will soon implement:

DrawPlayer: Draws the player’s tank.

DrawAliens: Draws all aliens.

DrawBullets: Draws all bullets (both the player’s and the aliens’).

DrawForeground: Draws the clouds that appear at the top of the screen.

DrawBackground: Draws the grass, hills, mountains, and sun/moon. Also handles transitioning between day and night.

Page | 38

©2011 Microsoft Corporation. All rights reserved.

Page 39: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

DrawHud: Draws the score elements, lives remaining, and the “GAME OVER” prompt when needed.

DrawString: A generic method for drawing shadowed text. It does not appear above, but we will require it.

12. Add the DrawPlayer method:

C#

void DrawPlayer(){ if (!gameOver && player.IsAlive) { spriteBatch.Draw(tankTexture, player.Position, Color.White); }}

13. Add the DrawAliens method:

C#

void DrawAliens(){ for (int i = 0; i < aliens.Count; ++i) { if (aliens[i].IsAlive) spriteBatch.Draw(aliens[i].Texture, new Rectangle((int)aliens[i].Position.X, (int)aliens[i].Position.Y, (int)aliens[i].Width, (int)aliens[i].Height), Color.White); }}

14. Add the DrawBullets method:

C#

private void DrawBullets(){ for (int i = 0; i < playerBullets.Count; ++i) { if (playerBullets[i].IsAlive) spriteBatch.Draw(bulletTexture, playerBullets[i].Position, Color.White); }

for (int i = 0; i < alienBullets.Count; ++i) { if (alienBullets[i].IsAlive) spriteBatch.Draw(laserTexture, alienBullets[i].Position, Color.White); }

Page | 39

©2011 Microsoft Corporation. All rights reserved.

Page 40: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

}

15. Add the DrawForeground method:

C#

private void DrawForeground(float elapsedTime){ // Move the clouds. Movement is typically update-related, but these animations // have no impact over gameplay. cloud1Position += new Vector2(24.0f, 0.0f) * elapsedTime; if (cloud1Position.X > screenWidth) cloud1Position.X = -cloud1Texture.Width * 2.0f;

cloud2Position += new Vector2(16.0f, 0.0f) * elapsedTime; if (cloud2Position.X > screenWidth) cloud2Position.X = -cloud1Texture.Width * 2.0f;

spriteBatch.Draw(cloud1Texture, cloud1Position, Color.White); spriteBatch.Draw(cloud2Texture, cloud2Position, Color.White);}

16. Add the DrawBackground method:

C#

private void DrawBackground(float elapsedTime){ transitionFactor += transitionRate * elapsedTime; if (transitionFactor < 0.0f) { transitionFactor = 0.0f; transitionRate = 0.0f; } if (transitionFactor > 1.0f) { transitionFactor = 1.0f; transitionRate = 0.0f; }

Vector3 day = Color.White.ToVector3(); Vector3 night = new Color(80, 80, 180).ToVector3(); Vector3 dayClear = Color.CornflowerBlue.ToVector3(); Vector3 nightClear = night;

Color clear = new Color(Vector3.Lerp(dayClear, nightClear, transitionFactor)); Color tint = new Color(Vector3.Lerp(day, night, transitionFactor));

// Clear the background, using the day/night color

Page | 40

©2011 Microsoft Corporation. All rights reserved.

Page 41: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

graphicsDevice.Clear(clear);

// Draw the mountains spriteBatch.Draw(mountainsTexture, new Vector2(0, screenHeight - mountainsTexture.Height), tint);

// Draw the hills spriteBatch.Draw(hillsTexture, new Vector2(0, screenHeight - hillsTexture.Height), tint);

// Draw the ground spriteBatch.Draw(groundTexture, new Vector2(0, screenHeight - groundTexture.Height), tint);

// Draw the sun or moon (based on time) spriteBatch.Draw(sunTexture, sunPosition, new Color(255, 255, 255, (byte)(255.0f * (1.0f - transitionFactor)))); spriteBatch.Draw(moonTexture, sunPosition, new Color(255, 255, 255, (byte)(255.0f * transitionFactor)));}

17. Add the DrawHud method:

C#

void DrawHud(){ float scale = 2.0f;

if (gameOver) { Vector2 size = menuFont.MeasureString("GAME OVER"); DrawString(menuFont, "GAME OVER", new Vector2(graphicsDevice.Viewport.Width / 2 - size.X, graphicsDevice.Viewport.Height / 2 - size.Y / 2), new Color(255, 64, 64), scale);

} else { int bonus = 100 * (hitStreak / 5); string bonusString = (bonus > 0 ? " (" + bonus.ToString(System.Globalization.CultureInfo.CurrentCulture) + "%)" : ""); // Score DrawString(scoreFont, "SCORE: " + player.Score.ToString(System.Globalization.CultureInfo.CurrentCulture) + bonusString, new Vector2(leftOffset, topOffset), Color.Yellow, scale);

Page | 41

©2011 Microsoft Corporation. All rights reserved.

Page 42: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

string text = "LIVES: " + player.Lives.ToString(System.Globalization.CultureInfo.CurrentCulture); Vector2 size = scoreFont.MeasureString(text); size *= scale;

// Lives DrawString(scoreFont, text, new Vector2(screenWidth - leftOffset - (int)size.X, topOffset), Color.Yellow, scale);

DrawString(scoreFont, "LEVEL: " + (((baseLevelKillCount - 5) / 5) + 1).ToString(System.Globalization.CultureInfo.CurrentCulture), new Vector2(leftOffset, screenHeight - bottomOffset), Color.Yellow, scale);

text = "HIGH SCORE: " + highScore.ToString(System.Globalization.CultureInfo.CurrentCulture);

size = scoreFont.MeasureString(text);

DrawString(scoreFont, text, new Vector2(screenWidth - leftOffset - (int)size.X * 2, screenHeight - bottomOffset), Color.Yellow, scale); }}

18. Add the DrawString method:

C#

void DrawString(SpriteFont font, string text, Vector2 position, Color color, float fontScale){ spriteBatch.DrawString(font, text, new Vector2(position.X + 1, position.Y + 1), Color.Black, 0, new Vector2(0, font.LineSpacing / 2), fontScale, SpriteEffects.None, 0); spriteBatch.DrawString(font, text, position, color, 0, new Vector2(0, font.LineSpacing / 2), fontScale, SpriteEffects.None, 0);}

19. We have finished implementing the game’s drawing logic. Navigate to the HandleInput method and replace the “TODO” comment inside it with the following code:

C#

if (pauseGame){ if (gameOver == true) { return true; } else {

Page | 42

©2011 Microsoft Corporation. All rights reserved.

Page 43: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

return false; }}else{ bool buttonTouched = false;

//interpret touch screen presses foreach (TouchLocation location in touchInfo) { switch (location.State) { case TouchLocationState.Pressed: buttonTouched = true; break; case TouchLocationState.Moved: break; case TouchLocationState.Released: break; } }

float movement = 0.0f;

if (Math.Abs(acceleration.X) > 0.10f) { if (acceleration.X > 0.0f) movement = 1.0f; else movement = -1.0f; }

player.Velocity.X = movement;

if (buttonTouched) { if (player.FireTimer <= 0.0f && player.IsAlive && !gameOver) { Bullet bullet = CreatePlayerBullet(); bullet.Position = new Vector2((int)(player.Position.X + player.Width / 2) - bulletTexture.Width / 2, player.Position.Y - 4); bullet.Velocity = new Vector2(0, -256.0f); player.FireTimer = 1.0f;

particles.CreatePlayerFireSmoke(player); playerFired.Play(); } else if (gameOver) {

Page | 43

©2011 Microsoft Corporation. All rights reserved.

Page 44: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

return true; } }}

The above code updates the player’s velocity according to the device’s tilt as received from the accelerometer (remember that accelerometer readings are fed to this method in the gameplay screen), and fires bullets when the player taps the device’s display.

20. All that is left to do to have a functional version of the game is update the Start method. Replace the “TODO” comment contained in that method with the following code:

C#

cloud1Position = new Vector2(224 - cloud1Texture.Width, 32);cloud2Position = new Vector2(64, 80);

sunPosition = new Vector2(16, 16);

player.Width = tankTexture.Width;player.Height = tankTexture.Height;

player.Score = 0;player.Lives = 3;player.IsAlive = true;player.RespawnTimer = 0.0f;player.Position = new Vector2(worldBounds.Width / 2 - player.Width / 2, worldBounds.Bottom - groundTexture.Height + 2 - player.Height);

particles.ResetParticles();

gameOver = false;

aliens.Clear();alienBullets.Clear();playerBullets.Clear();

transitionRate = 0.0f;transitionFactor = 0.0f;levelKillCount = 5;baseLevelKillCount = 5;alienScore = 25;alienSpawnRate = 1.0f;

alienMaxAccuracy = 0.25f;

alienSpeedMin = 24.0f;alienSpeedMax = 32.0f;

alienSpawnRate = 2.0f;

Page | 44

©2011 Microsoft Corporation. All rights reserved.

Page 45: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

alienSpawnTimer = alienSpawnRate;

nextLife = 5000;

21. We now have a playable version of the game, though there is no way to pause or quit the game short of terminating it through the debugger. Let us fix this by first adding a pause screen. The pause screen is very similar to the main menu screen, so simply add it to the AlienGame project from the lab’s Source\Assets\Code folder. The file in question is PauseScreen.cs.

22. Open GameplayScreen.cs and navigate to the GameplayScreen’s HandleInput method. Replace the first “TODO” comment in the method with the following code:

C#

FinishCurrentGame();

23. Replace the second “TODO” comment with the following code:

C#

PauseCurrentGame();

24. Add the helper methods used in the two previous steps:

C#

private void PauseCurrentGame(){ ScreenManager.AddScreen(new BackgroundScreen()); ScreenManager.AddScreen(new PauseScreen());}

private void FinishCurrentGame(){ ExitScreen();}

25. Compile and run the game, and select “Start Game” and see the game in action.

Page | 45

©2011 Microsoft Corporation. All rights reserved.

Page 46: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

Figure 6The fully functional game screen.

Note: When in the game screen, tap the screen to fire bullets and tilt the device left or right to move the tank accordingly. If you are using the emulator, accelerometer input can be emulated by the process described in the following link: http://msdn.microsoft.com/en-us/library/hh202936(v=vs.92).aspx.

Page | 46

©2011 Microsoft Corporation. All rights reserved.

Page 47: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

Figure 7The game’s pause screen

During this task, you implemented the game’s logic and ended up with a fully playable game.

Task 5 – Lifetime event handling

While our game is complete where actual gameplay is concerned, it does not handle events related to the application’s lifecycle, such as having the game deactivated or reactivated, be it by the user or by a device related event such as an incoming call. In this task, we will change the game to handle activation and deactivation properly.

1. We will begin by implementing serialization and deserialization in the gameplay helper. Open GameplayHelper.cs and add the following parameterless constructor to the GameplayHelper class:

C#

public GameplayHelper(){ random = new Random();

Page | 47

©2011 Microsoft Corporation. All rights reserved.

Page 48: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

worldBounds = new Rectangle(0, 0, (int)screenWidth, (int)screenHeight);

gameOver = true;

player = new Player(); playerBullets = new List<Bullet>();

aliens = new List<Alien>(); alienBullets = new List<Bullet>();

particles = new ParticleSystem();}

2. Navigate to the ReadXml method and replace the “TODO” comment contained inside it with the following code:

C#

// Read the wrapper elementreader.Read();

// deserialize basic gameplay elementsDeserializeGameplayMembers(reader);

// Deserialize the particle systemXmlSerializer particleSystemSerializer = new XmlSerializer(typeof(ParticleSystem));particles = particleSystemSerializer.Deserialize(reader) as ParticleSystem;

// Deserialize the playerXmlSerializer playerSerializer = new XmlSerializer(typeof(Player));player = playerSerializer.Deserialize(reader) as Player;

// Deserialize the various bulletsXmlSerializer bulletSerializer = new XmlSerializer(typeof(Bullet));

int playerBulletCount = int.Parse(reader.GetAttribute("Count"));

// Read past the opening element for the player bullet list reader.Read();

for (int i = 0; i < playerBulletCount; i++){ playerBullets.Add(bulletSerializer.Deserialize(reader) as Bullet);}

// Advance past the closing element if it existsif (playerBulletCount > 0)

Page | 48

©2011 Microsoft Corporation. All rights reserved.

Page 49: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

{ reader.Read();}

int alienBulletCount = int.Parse(reader.GetAttribute("Count"));

// Read past the opening element for the alien bullet listreader.Read();

for (int i = 0; i < alienBulletCount; i++){ alienBullets.Add(bulletSerializer.Deserialize(reader) as Bullet);}

// Advance past the closing element if it existsif (alienBulletCount > 0){ reader.Read();}

// Deserialize the aliensXmlSerializer alienSerializer = new XmlSerializer(typeof(Alien));

int alienCount = int.Parse(reader.GetAttribute("Count"));

// Read past the opening element for the alien listreader.Read();

for (int i = 0; i < alienCount; i++){ aliens.Add(alienSerializer.Deserialize(reader) as Alien);}

// Advance past the closing element if it existsif (alienCount > 0){ reader.Read();}

reader.Read();

3. Use the following code to add the DeserializeGameplayMembers helper method and the DeserializeVector method, which it uses:

C#

private void DeserializeGameplayMembers(XmlReader reader){ gameOver = reader.ReadElementContentAsBoolean("GameOver", SerializationNamespace);

Page | 49

©2011 Microsoft Corporation. All rights reserved.

Page 50: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

baseLevelKillCount = reader.ReadElementContentAsInt("BaseLevelKillCount", SerializationNamespace); levelKillCount = reader.ReadElementContentAsInt("LevelKillCount", SerializationNamespace); alienSpawnTimer = reader.ReadElementContentAsFloat("AlienSpawnTimer", SerializationNamespace); alienSpawnRate = reader.ReadElementContentAsFloat("AlienSpawnRate", SerializationNamespace); alienMaxAccuracy = reader.ReadElementContentAsFloat("AlienMaxAccuracy", SerializationNamespace); alienSpeedMin = reader.ReadElementContentAsFloat("AlienSpeedMin", SerializationNamespace); alienSpeedMax = reader.ReadElementContentAsFloat("AlienSpeedMax", SerializationNamespace); alienScore = reader.ReadElementContentAsInt("AlienScore", SerializationNamespace); nextLife = reader.ReadElementContentAsInt("NextLife", SerializationNamespace); hitStreak = reader.ReadElementContentAsInt("HitStreak", SerializationNamespace); highScore = reader.ReadElementContentAsInt("HighScore", SerializationNamespace);

transitionFactor = reader.ReadElementContentAsFloat("TransitionFactor", SerializationNamespace); transitionRate = reader.ReadElementContentAsFloat("TransitionRate", SerializationNamespace);

cloud1Position = DeserializeVector(reader); cloud2Position = DeserializeVector(reader); sunPosition = DeserializeVector(reader);}

private Vector2 DeserializeVector(XmlReader reader){ Vector2 result = new Vector2(float.Parse(reader.GetAttribute("X")), float.Parse(reader.GetAttribute("Y"))); reader.Read(); return result;}

4. Now let us move to handling serialization. Navigate to the WriteXml method and replace the “TODO” comment contained inside it with the following code:

C#

Page | 50

©2011 Microsoft Corporation. All rights reserved.

Page 51: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

// Serialize basic gameplay elementsSerializeGameplayMembers(writer);

// Serialize the particle systemXmlSerializer particleSystemSerializer = new XmlSerializer(typeof(ParticleSystem));particleSystemSerializer.Serialize(writer, particles);

// Serialize the playerXmlSerializer playerSerializer = new XmlSerializer(typeof(Player));playerSerializer.Serialize(writer, player);

// Serialize the various bulletsXmlSerializer bulletSerializer = new XmlSerializer(typeof(Bullet));

writer.WriteStartElement("PlayerBullets");

writer.WriteAttributeString("Count", playerBullets.Count.ToString());

foreach (Bullet bullet in playerBullets){ bulletSerializer.Serialize(writer, bullet);}

writer.WriteEndElement();

writer.WriteStartElement("AlienBullets");

writer.WriteAttributeString("Count", alienBullets.Count.ToString());

foreach (Bullet bullet in alienBullets){ bulletSerializer.Serialize(writer, bullet);}

writer.WriteEndElement();

// Serialize the aliensXmlSerializer alienSerializer = new XmlSerializer(typeof(Alien));

writer.WriteStartElement("Aliens");

writer.WriteAttributeString("Count", aliens.Count.ToString());

foreach (Alien alien in aliens){ alienSerializer.Serialize(writer, alien);}

Page | 51

©2011 Microsoft Corporation. All rights reserved.

Page 52: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

writer.WriteEndElement();

5. Much as we did when adding deserialization logic, add a pair of helper methods – SerializeGameplayMembers and SerializeVector:

C#

private void SerializeGameplayMembers(XmlWriter writer){ writer.WriteElementString("GameOver", gameOver.ToString().ToLowerInvariant()); writer.WriteElementString("BaseLevelKillCount", baseLevelKillCount.ToString()); writer.WriteElementString("LevelKillCount", levelKillCount.ToString()); writer.WriteElementString("AlienSpawnTimer", alienSpawnTimer.ToString()); writer.WriteElementString("AlienSpawnRate", alienSpawnRate.ToString()); writer.WriteElementString("AlienMaxAccuracy", alienMaxAccuracy.ToString()); writer.WriteElementString("AlienSpeedMin", alienSpeedMin.ToString()); writer.WriteElementString("AlienSpeedMax", alienSpeedMax.ToString()); writer.WriteElementString("AlienScore", alienScore.ToString()); writer.WriteElementString("NextLife", nextLife.ToString()); writer.WriteElementString("HitStreak", hitStreak.ToString()); writer.WriteElementString("HighScore", highScore.ToString());

writer.WriteElementString("TransitionFactor", transitionFactor.ToString()); writer.WriteElementString("TransitionRate", transitionRate.ToString());

SerializeVector(writer, "Cloud1Position", cloud1Position); SerializeVector(writer, "Cloud2Position", cloud2Position); SerializeVector(writer, "SunPosition", sunPosition);}

private void SerializeVector(XmlWriter writer, string elementName, Vector2 vector){ writer.WriteStartElement(elementName); writer.WriteAttributeString("X", vector.X.ToString()); writer.WriteAttributeString("Y", vector.Y.ToString()); writer.WriteEndElement();}

Page | 52

©2011 Microsoft Corporation. All rights reserved.

Page 53: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

6. As we are in the process of handling the game’s persistence, this would be a good time to introduce methods for saving and loading the game’s high-score. Use the following code to add the SaveHighscore and LoadHighscore methods, which store a single integer value in isolated storage as the game’s high-score.

C#

private void SaveHighscore(){ using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream("highscores.txt", FileMode.Create, isf)) { using (StreamWriter writer = new StreamWriter(isfs)) { writer.Write(highScore.ToString(System.Globalization.CultureInfo.InvariantCulture)); writer.Flush(); writer.Close(); } } }}

private void LoadHighscore(){ using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { if (isf.FileExists("highscores.txt")) { using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream("highscores.txt", FileMode.Open, isf)) { using (StreamReader reader = new StreamReader(isfs)) { try { highScore = Int32.Parse(reader.ReadToEnd(), System.Globalization.CultureInfo.InvariantCulture); } catch (FormatException) { highScore = 10000; } finally

Page | 53

©2011 Microsoft Corporation. All rights reserved.

Page 54: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

{ if (reader != null) reader.Close(); } } } } }}

7. Navigate to the LoadContent method and replace the “TODO” comment contained inside it with the following code:

C#

LoadHighscore();

8. Add the following cleanup method, called UnloadContent. We will use it for saving the game’s high-score as well:

C#

public void UnloadContent(){ SaveHighscore();

particles = null;}

9. Open LoadingScreen.cs and navigate to the Update method. In order to handle a case where the pause screen needs to display after loading (for instance, reactivate the game after it has been deactivated while the gameplay screen was displayed), replace the “TODO” comment in this method with the following code:

C#

ScreenManager.AddScreen(new PauseScreen());

10. Open AlienGame.cs and locate the AlienGame class’s Game_Closing method. Replace the “TODO” comment inside the method with the following code:

C#

if (PhoneApplicationService.Current.State.ContainsKey(GameStateKey)){ (PhoneApplicationService.Current.State[GameStateKey] as GameplayHelper).UnloadContent();}

11. In the Game_Activated method, replace the “TODO” comment with the following code:

C#

ReloadRequired = !e.IsApplicationInstancePreserved;

Page | 54

©2011 Microsoft Corporation. All rights reserved.

Page 55: Game Development with XNA Frameworkaz12722.vo.msecnd.net/.../GameDevelopmentWithXNA.docx  · Web viewThis lab introduces you to XNA Game Studio game development on Windows Phones,

if (!ReloadRequired){ // The instance was preserved, so use the local member which was not serialized PhoneApplicationService.Current.State[GameStateKey] = GameplayHelper;}

bool isInGame = (bool)PhoneApplicationService.Current.State[InGameKey];

if (!e.IsApplicationInstancePreserved || (isInGame && (screenManager.GetScreens().Last() is GameplayScreen))){ screenManager.AddScreen(new BackgroundScreen()); screenManager.AddScreen(new LoadingScreen(isInGame));}

The above code initializes some of the game’s elements depending on whether or not the game’s deactivated instance was preserved.

Note: For a review of the Windows Phone’s application lifecycle, see the following link: http://msdn.microsoft.com/en-us/library/ff817008(v=vs.92).aspx.

Note: The complete solution for this exercise is located at theSource\Ex1-AlienGame\End folder of this lab.

In this task, you altered the game so that it may properly handle application lifecycle events.

Summary

This lab introduced you to developing applications for the Windows Phone platform using the XNA Framework. During the course of this lab, you created an XNA Game Studio game for Windows Phone, loaded the game’s resources, took care of the input, updated the game state, added game specific logic and made sure that the game can handle lifecycle events.

By completing this hands-on lab, you also became familiar with the tools required to create and test a Windows Phone XNA Game Studio game.

Page | 55

©2011 Microsoft Corporation. All rights reserved.