Adding a main menu

Article by Matthew Casperson (4,877 pts ) , published Jul 7, 2009

In this article we add some structure to the game by implementing a main menu screen.

Almost every game displays a main menu before the game itself is run. Up until now our JavaScript game has launched right into the game itself. It would be nice if we could display a menu first that gives some information about the game before it is run.

The first thing we need to do in order to implement a main menu is to enable all the current game objects that are running to be removed all at once. This may seem backwards, but it makes sense when you consider that the main menu will be displayed before the game is played and also when it has ended. Obviously we don’t want to have the player running around on the main menu after the game has finished.

GameObjectManager.js

The GameObjectManager class gains a few new functions to facilitate this ability to remove all current game objects: shutdownAll, removeOldGameObjects and addNewGameObjects.

The shutdownAll function is quite simple. It loops through the current collection of GameObjects and calls their shutdown function. This cleans up their resources and removed them from the game. [code]

The removeOldGameObjects and addNewGameObjects functions have been added to avoid a situation where the main gameObjects collection is modified while it is being looped over. This can occur because an instance of the GameObject class is created or removed during a call to its update function. As an example, this can happen when a powerup collides with the player. The powerup will eventually call the shutdownGameObject function, which removed the GameObject from the main gameObjects collection. By placing new and removed GameObjects into placeholder collections, and then syncing them to main gameObjects collection outside of any code that loops over the gameObjects collection, we can ensure that we don’t get any of the hard to track down bugs that can occur when you modify a collection while looping over it. The Array.clear function was provided by the prototype javascript framework. [code]

Finally, a small change needs to be made to the draw function to call the removeOldGameObjects and addNewGameObjects functions, ensuring that the gameObjects collection is kept in sync. [code]

ApplicationManager.js

The ApplicationManager is then modified to include two new functions: startLevel and openMainMenu.

The startLevel function initializes the objects needs to create the game. This code was originally in the startupApplicationManager function. [code]

The openMainMenu function creates a new instance of the new MainMenu class. Both the startLevel and openMainMenu functions call the GameObjectManager shutdownAll function to ensure the application has a clean slate before creating their respective objects. [code]

Subscribe to Web Development
RSS
Get free weekly updates, directly to your inbox.
Browse Web Development