Thursday, February 08, 2007

A general GameScreen implementation

A few weeks ago, Eli posted a design for a GameScreen and a GameScreenManager to use in XNA. The GameScreen is a base class, like Game, that implements one layer of a game (e.g. the game itself, or a menu, or a title screen). The GameScreenManager is used by the Game class to switch between these screens using a stack-based design. I ended up implementing this design for my book, and I've been using a few weeks with no problems so I thought I'd post it here for the XNA community to use. To use the GameScreenManager, declare a public instance of it on your Game object, along with any screens that are spawned by Game and not by other screens. public GameScreenManager screenManager; // Screens StartMenuScreen menuscreen; PlayScreen play; public Game1() {

... screenManager = new GameScreenManager(2); ...
} Add the first screen during Game.Initialize() by creating the screen, initializing it, and calling GameScreenManager.Push. I also create the other screen at this point, but I don't initialize it until it's invoked. protected override void Initialize() {
// TODO: Add your initialization logic here play = new PlayScreen(this); play.Initialize(); screenManager.Push(play); menuscreen = new StartMenuScreen(this); ...
} At some point later, if the menu is invoked, I initialize it and push it over top of the play screen: // if the menu isn't already up if (screenManager.Peek() != menuscreen) { GamePad.SetVibration(PlayerIndex.One, 0, 0); // install menu screen menuscreen.Initialize(); screenManager.Push(menuscreen); Lastly, when the menu is finished, I fire an event back Game, which removes it. public void MenuScreenFinished(int Selection) {
screenManager.Pop(); if (Selection == 0) return; if (Selection == 1) { play.ResetGame(); } if (Selection == 2) { this.Exit(); }
}
You can download the GameScreen.cs and a sample screen here. Also, I should probably hawk the fact that my book is available for pre-order.

Labels: ,

0 Comments:

Post a Comment

<< Home