ShackRPG: Screen Manager
For every game that has more than one game screen, you need a way to manage those screens. Even the old games such as Super Mario Bros or before that, Pong.. They often had at least two screens, sometimes more.
1) Main Menu Screen – Select players, show splash screen
2) Game Screen – Handles all game logic and render the game to screen
3) Credits – shows the names of all the developers and any final messages
4) Game Over – displays a Game Over screen and asks if you wish to continue
For a game with so few screens, you could simply just load them as you need them in a stack or, *shutter*, a few switch blocks in a main Update() method. With a game as complex as an action RPG such as my project, that won’t work. And thus, the ScreenManager class was born.
This class is based off of the XNA Websites GameScreenManager sample, with various changes to suit my needs. Each screen in the game inherits from a GameScreen class, and is then loaded into a few lists in the Screen Manager.
List<GameScreen> screens = new List<GameScreen>();
List<GameScreen> screensToUpdate = new List<GameScreen>();
List<GameScreen> screensToRemove = new List<GameScreen>();
Every GameScreen loaded to memory is in the Screens list, and only those screens needing to be updated is filtered into the screensToUpdate list. If a screen is needing to be removed (such as if you’re finished editing your map, and wish to exit the map editor and play it in the game) that screen is added to the screens to remove list.
Inside the screen manager, there are a few methods designed to keep the game screens in order; these are
AddScreen(GameScreen screen) – Adds a new game screen into the game
RemoveScreen(GameScreen screen) – Removes a game screen from the game
RemoveScreen(string asset) – Removes the game screen with the name you specify
the above methods are public, and are accessible anywhere within the program, and one private method that is only accessible from within the Screen Manager class is the ClearRemovedScreens(), which takes all the screens from the screensToRemove list and unloads all textures, sounds, and other assets associated with that gamescreen from memory, and finally removes that screen from the lists.
The only thing left to do now, is Update all screens needing to be updated, and render all screens to the screen. That is the job of our next two methods, ironically called “Update” and “Draw”
public void Update()
public void Draw()
In a nutshell, this is our screen class.
Link to full source code: Click Here