In this article we add state management, and a main menu.
At this point we have a player, some enemies, the start of an implementation to add the enemies to the screen, collision detection and weapons. The last piece of functionality that we need in order to make this a playable game is the ability to define states.
The game will have a number of states. It will have a state where it shows the main menu, a state where the game is being played and state where you see the high scores. What we need is a way to easily switch between these states.
StateManager.cpp / StateManager.h
The StateManager class is used to manage the game states. It contains a database of state names. Two functions can be registered for each state, one called when the state is entered, and the other when it is left.
The StateManager makes use of the function and bind classes provided by the boost library. The combination of these classes effectively gives C++ the ability to create an use delegates, which are basically function pointers to functions in unspecified objects. By default C++ only supports function pointers either to stand alone functions, static functions, or functions within a specific class type. I recommend you read these pages here for a more detailed explanation.
ApplicationManager.cpp / ApplicationManager.h
The ApplicationManager was created from the beginning to hold the logic that defines how the game is run. In practise this means that it is the second half to the StateManager – the ApplicationManager holds the code to populate the states with the appropriate objects, and the StateManager provides the functionality to switch between these states.
In the Startup function we map several functions to states by calling the StateManagers RegisterStateChange function. This registered two function against each state. The first is called when the state is entered, the second when the state is left.