IT tutorials
 
Mobile
 

Windows Phone 7 : Building 2D Games with the XNA Framework (part 1)

4/26/2013 9:29:20 PM
- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019

1. Xbox LIVE Gamer Services

A hot topic of interest to indie game developers is access to Xbox LIVE gamer services. Xbox LIVE gamer services provide matchmaking, Achievements, Leaderboards, etc. support to Xbox games. You can find more information here:

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.gamerservices.aspx

					  

On Windows Phone 7, a subset of Xbox LIVE gamer services is available to Xbox LIVE publishers. Example Xbox Live game publishers are Microsoft Game Studios, Electronic Arts, and Gameloft. Generally, a game developer works with an existing Xbox LIVE game publisher to ship a game that includes Xbox LIVE gamer services. It is difficult for a new game developer to immediately become an Xbox LIVE game publisher. It is a high bar; just look at the names of existing publishers.

So for an indie game developer, create an awesome game or possibly a fully fleshed out concept as the first step to gain access to Xbox LIVE gamer services. The next step is to get your game in front of an existing Xbox LIVE game publisher. Microsoft Game Studios currently has an e-mail alias to which you can send proposals: [email protected]. The other way to get noticed is to submit your finished game to AppHub and climb the popularity charts. An existing proven success as an indie publisher will help you get noticed.

Don't lose hope if you have your heart set on Xbox LIVE gamer services. Initially, the services were not available to Xbox Indie game publishers as part of create.msdn.com, but the services were eventually made available to indie game publishers on big Xbox. One can hope that in the future more Xbox LIVE gamer services become available to indie developers on Windows Phone 7 as well.

2. Alien Shooter

The sample covered game loop basics with a very simple UI that had a hero ship that shot a missile at the alien attacker ship. As you recall, XNA is not event driven. Rather, it checks status on objects and input (polls) in a type loop that tries to ensure that the screen is drawn at 30 frames/second. Frame rate can drop if a game spends too much time "thinking" when updating objects. Here is a summary of how this works:

while (Game.IsRunning)
{
  Update();  //Perform calculations, update objects, handle input
  Draw();  //Draw background, objects, effects
}

The HelloXNA sample isn't really much of a "game," because there wasn't any interactivity. It essentially loaded up content and initialized state in the Game.LoadContent method. The Update method did some screen bounds checking and reset objects when they flew off the screen, and then the objects were rendered in the Draw method. In the HelloXNA sample, you cannot move the hero ship and the one attacker appears on the screen at the same place. In this section we will turn it into a "real" game with a menu, score, movable hero ship, and more worthy opponents in the alien attackers.

The AlienShooter game will include a main menu, options menu, and actual game play. We introduce a Game Management sample that provides a ScreenManager class, a Menu class, and GameScreen objects to manage game functions. The game is modularized into individual screen classes, so you can have a screen that shows the main menu, a screen that shows the options for the game, and so on, as well as a screen that actually handles game play. By following these best practices your game will have a professional look and feel as well as be more maintainable. In subsequent sections we cover how to add basic animations and effects to provide more interesting game play.

3. From Demo to Game

This section covers how to add the game management and screens to the AlienShooter sample project. The best way to start creating a "real" game is to base it on the Game State Management sample, which includes a main menu, an options screen, some gameplay, and a pause menu. It displays a loading screen between menus and gameplay with a popup message box to confirm that a user intends to quit. You can download the sample here:

http://create.msdn.com/en-US/education/catalog/sample/game_state_management

Right-click on the .zip and select "unblock" to ensure that security checks don't prevent you from being able to compile and run the application.


When you deploy the GameStateManagementSample (Phone) sample, notice that the game does not show up in the Games Hub, but is instead in the application list. The Genre attribute on the App element in the WMManifest.xml file determines where an application appears. The default is Genre="Apps.Normal" so that the application appears in the Application List. Change the genre attribute to Genre="Apps.Games" to have the game show up in the Games Hub.

Run the GameStateManagementSample (Phone) sample project to see the nice animations and transitions available with this sample. 

Close the Toolbox tool window to give yourself more space when working with XNA Game Studio games since there aren't components relevant in the Toolbox tool window.


With both the AlienShooter and GameStateManagementSample (Phone) sample projects open, we first create two new folders in AlienShooter named Screens and GameManagement. Copy the contents of the ScreenManager folder in the GameStateManagementSample (Phone) sample project to the GameManagement folder in the AlienShooter project. Copy the Screens folder content to the Screens folder content in the AlienShooter project.

Once copied over, select the option to Show All Files at the top of the Solutions Tool Window in Visual Studio. The next step is to right-click on the files in Visual Studio and select Include In Project to add them to the AlienShooter project. Be sure to fix up the namespaces by changing them from GameStateManagement to AlienShooter.GameManagement for the GameManagement folder content and to AlienShooter.Screens for the Screens folder content. You will also need to add a using AlienShooter.GameManagement; statement to all of the code files in the Screens folder as well. After fixing everything up the application should compile without any errors or warnings.

Next open the GameStateManagementSample (Phone) Content project folder and copy over all of the content files to the AlienShooterContent project folder using Windows Explorer except for the Content.contentproj file. As before, select the option to Show All Files in Visual Studio 2010, and then include the files into the AlienShooterContent project folder. We decide to split the content between GameManagement content and actual game content. Create a new folder in the AlienShooterContent project named GameManagement and copy menufont.spritefont and blank.png into the AlienShooterContent project GameManagement folder. The rest of the content is related to game play, which we will eventually replace anyway.

Next we go through the GameStateManagementSample (Phone) project'sGame1.cs and modify the AlienShooter Game1.cs to match the game state sample's Game.cs file. First, rename the Game1 class to AlienShooterGame and rename the code file Game1.cs to AlienShooterGame.cs. You will notice right away that the default spriteBatch private variable is not present in the game state sample, which suggests that the Game1.Draw and Game1.Update methods must not perform any game logic in this code file. Instead, there is a private field variable named screenManager of type ScreenManager that is added. Add a using AlienShooter.GameManagement; statement to the top of AlienshooterGame.cs as well.

We next move to the Constructor AlienShooterGame() and modify it to match the game state sample's GameStateManagementGame constructor as shown in Listing 1.

Example 1. AlienShooterGame Constructor
public AlienShooterGame()
{
  graphics = new GraphicsDeviceManager(this);
  Content.RootDirectory = "Content";
  TargetElapsedTime = TimeSpan.FromTicks(333333);

  // you can choose whether you want a landscape or portrait
  // game by using one of the two helper functions defined below
  InitializePortraitGraphics();
  // InitializeLandscapeGraphics();

  // Create the screen manager component.
  screenManager = new ScreenManager(this);

  Components.Add(screenManager);

  // attempt to deserialize the screen manager from disk. if that
  // fails, we add our default screens.
  if (!screenManager.DeserializeState())
  {
    // Activate the first screens.
    screenManager.AddScreen(new BackgroundScreen(), null);
    screenManager.AddScreen(new MainMenuScreen(), null);
  }
}

The code file defines two helper functions that set whether the game is a portrait or landscape game. Listing 2 has the code for the two helper functions.

Example 2. Helper Functions to Configure Portrait or Landscape Game
private void InitializePortraitGraphics()
{
  graphics.PreferredBackBufferWidth = 480;
  graphics.PreferredBackBufferHeight = 800;
}

private void InitializeLandscapeGraphics()
{
  graphics.PreferredBackBufferWidth = 800;
  graphics.PreferredBackBufferHeight = 480;
}

The next bit of code in Listing 7-1 for the AlienShooterGame constructor creates the ScreenManager and then adds it to the Components collection for the Microsoft.Xna.Framework.Game base class.

Component classes inherit from the Microsoft.Xna.Framework.DrawableGameComponent class, which attempts to modularize game development by providing the ability to have objects Update and Draw themselves without forcing all of that logic into the default Game.Draw and Game.Update methods. The ScreenManager class inherits from DrawableGameComponent and handles all of the actual Draw and Update logic for the game. I cover the ScreenManager class in detail in just a bit, so let's continue updating our AlienShooterGame (formerly Game1.cs) code file to get our game up and running. The last section of the AlienShooterGame constructor attempts to load the ScreenManager instance from disk. If it cannot, it loads the default screens to start the game.

The code overrides Game.OnExiting to serialize game state to disk in this event handler to set up state for the next time the game launches.

protected override void OnExiting(object sender, System.EventArgs args)
{
  // serialize the screen manager whenever the game exits
  screenManager.SerializeState();

  base.OnExiting(sender, args);
}

For our new version of the application, we use the ScreenManager to do work for us so we remove the LoadContent, UnloadContent, and Update methods from AlienShooterGame.cs. We modify Game.Draw to set the background color to Color.Black from Color.CornflowerBlue but otherwise this completes our edits for this file.

In order to test our work, we need to modify where GameManagement content is loaded from because remember that we placed that content inside of a GameManagement folder in the AlienShooterContent project. Open up the ScreenManager class and find the LoadContent override. Modify the load locations like this:

font = content.Load<SpriteFont>("GameManagement/menufont");
blankTexture = content.Load<Texture2D>("GameManagement/blank");

Once the above edits are completed, test and run and the AlienShooter project should work just like the GameStateManagementSample (Phone) sample project with a bit of code and content reorganization under the covers. You can choose to follow these steps by hand in your project or simply grab the AlienShooter project and rename the namespaces, game class, and screen classes to match your application. In the next section we go through the Game Management related classes located in the GameManagement folder to help you understand what's going on under the covers so that you can further customize the game to meet your needs.

3.1. Game Management

The GameManagement folder contains three class files, GameScreen.cs, InputState.cs, and ScreenManager.cs. The ScreenManager class orchestrates loading GameScreen objects and transitions between GameScreen objects for you. The GameScreen abstract base class contains all of the underlying plumbing code to plug into the Game Management framework and is the base class for objects declared in the Screens folder. The InputState class collects Keyboard, Gamepad, and TouchPanel inputs. For Windows Phone 7, TouchPanel input is primary, though some devices support a keyboard as well. Figure 1 shows the class diagram for the Game Management classes.

Figure 1. Game Management framework

The ScreenManager class is a DrawableGameComponent, while the GameScreen base class is not. The ScreenManager manages one or more screen classes that inherit from GameScreen. ScreenManager maintains a stack of screens, calls their Update and Draw methods at the appropriate times, and automatically routes input to the top most active screen.

You will notice that DrawableGameComponent looks very similar to the Game class. There are method overrides available for LoadContent, UnloadContent, Update, and Draw, much like the Game class. Under the covers the XNA Framework keeps the main Game class and available DrawableGameComponents in sync with respect to the Update and Draw methods, so that the developer can just focus on each individual component and screen.

In the ScreenManager.Draw and ScreenManager.Update methods, each screen is given an opportunity to process input, and either Update or Draw itself if it is the active screen. The ScreenManager's framework provides nice transition support for fade-in and fade-out of screens as the user navigates the game. If you like the way things work as is, you can just focus on your menu, options, game play screen, etc., and the framework takes care of the rest.

3.2. Screens and Menus

Now that we have covered the game management plumbing provided by the ScreenManager class, we will switch focus to the UX aspects of screens and menu. There are several screens in the project that were copied over from the Game Management sample that provide the starter UI. We go through these screens in this section.

The BackgroundScreen class sits behind all of the other menu screens. It draws a background image that remains fixed in place regardless of whatever transitions that other screens may implement. The content that is loaded is the background.png. Swap the background.png file with your default background image.

The MainMenuScreen class is the first screen that is loaded by the game. It displays the main menu items of Play and Options. The OptionsMenuScreen class is displayed over the main menu screen. It provides the user a chance to configure the game. Figure 2 shows the default Main Menu and Options Menu screens.

Figure 2. Main Menu and Options Menu

The menu items have a nice "Metro" transition when flying in and out. Individual menu items are still graphic items with additional logic to detect a touch and fire an event. The MenuEntry class provides menu item functionality. Here is the constructor for the OptionsMenuScreen class:

public OptionsMenuScreen()
    : base("Options")
{
    // Create our menu entries.
    ungulateMenuEntry = new MenuEntry(string.Empty);

languageMenuEntry = new MenuEntry(string.Empty);
    frobnicateMenuEntry = new MenuEntry(string.Empty);
    elfMenuEntry = new MenuEntry(string.Empty);

    SetMenuEntryText();

    // Hook up menu event handlers.
    ungulateMenuEntry.Selected += UngulateMenuEntrySelected;
    languageMenuEntry.Selected += LanguageMenuEntrySelected;
    frobnicateMenuEntry.Selected += FrobnicateMenuEntrySelected;
    elfMenuEntry.Selected += ElfMenuEntrySelected;

    // Add entries to the menu.
    MenuEntries.Add(ungulateMenuEntry);
    MenuEntries.Add(languageMenuEntry);
    MenuEntries.Add(frobnicateMenuEntry);
    MenuEntries.Add(elfMenuEntry);
}

The MenuEntries collection in the OptionsMenuScreen constructor is a protected member of the MenuScreen base class for the MainMenuScreen and OptionsMenuScreen classes. The MenuScreen.Draw and MenuScreen.Update methods measure and position menu entries for drawing to the screen. The MenuScreen class includes the sliding transitions logic for menu items in case you want to modify it.

Click on a menu item to view the transition to a new screen. The loading screen inherits from the GameScreen class coordinates transitions between the menu system and the game itself. Normally one screen will transition off at the same time as the next screen is transitioning on, but for larger transitions that can take a longer time to load their data; we want the menu system to be entirely gone before we start loading the game. This is done as follows:

  • Tell all the existing screens to transition off.

  • Activate a loading screen, which will transition on at the same time.

  • The loading screen watches the state of the previous screens.

  • When the loading screen sees they have finished transitioning off, it activates the real next screen, which may take a long time to load its data. The loading screen will be the only thing displayed while this load is taking place.

This concludes the overview of the Game Management ScreenManager, GameScreen, MenuScreen, and MenuEntry classes. In the next section we dive in and start to customize the template game for the AlienShooter game.

 
Others
 
- Android Application Development : Signing and Publishing Your Application (part 2)
- Android Application Development : Signing and Publishing Your Application (part 1)
- iPhone Developer : Assembling Views and Animations - View Hierarchies
- iPhone Developer : Creating an “Online” GameKit Connection
- Java ME on Symbian OS : Handling Transitions Between Foreground and Background
- Java ME on Symbian OS : Handling JSR Fragmentation
- IPad : Using Popular and Critical Apps - Using Bento
- IPad : Using Popular and Critical Apps - Using iTap VNC
- BlackBerry Development : Pushing Data to Internal Users - Browser Push
- BlackBerry Application Data Push : How the Application Data Push Process Works
 
 
Top 10
 
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
Technology FAQ
- Is possible to just to use a wireless router to extend wireless access to wireless access points?
- Ruby - Insert Struct to MySql
- how to find my Symantec pcAnywhere serial number
- About direct X / Open GL issue
- How to determine eclipse version?
- What SAN cert Exchange 2010 for UM, OA?
- How do I populate a SQL Express table from Excel file?
- code for express check out with Paypal.
- Problem with Templated User Control
- ShellExecute SW_HIDE
programming4us programming4us