Game Development Reference
In-Depth Information
Game states should be run completely independently. In other words, we do not
want to have to deal with the options menu screen or the game over screen while
we are in the game playing state.
There should be an easy way to define game states, find game states and switch
between them. That way, when the player presses the 'options' button in the title
screen, we can easily switch to the option menu state.
We are going to follow the procedure where each game state has its own input
handling, update, and draw part, just like we did with game objects. It would be
nice, though, if we can somehow ensure a bit of consistency within our class design.
We could define a generic GameState class that has the same method headers for
handling input, updating and drawing as the GameObject class, but that is perhaps
not ideal, because apart from these method headers, we do not know anything else
about the particular game state. Another way to do this would be to let the game
states inherit from the GameObject class. However, this is not a good solution either,
since game states are not really game objects. For one, they do not need a position
or a velocity. As we have discussed early on in this topic, we should use object-
oriented design in such a way that subclasses are a special kind of the superclass
they inherit from.
21.2.1 A Generic Game Loop Object Interface
There is another way to ensure that the method headers are the same for objects that
follow the game loop principle: using an interface . In this interface, we then specify
which methods should be implemented by the class that is based on the interface.
Since we want an interface for any objects that partake in the game loop, let us
call this interface IGameLoopObject (we prefix the interface with an 'I' character to
separate it from regular class names). The IGameLoopObject interface contains four
methods, three of which are the main game loop methods ( HandleInput , Update and
Draw ), and a Reset method. The complete interface is given in Listing 21.1 . As you
will probably notice, we do not put the virtual keyword in front of methods in the
interface. We only use virtual and override when we are dealing with inheritance .
An interface simply specifies which methods should be defined in a class and what
their parameters and return value looks like.
Now that we have this interface, the first thing we do is make sure that all the
game objects also follow this interface. This was already (sort of) achieved in the
GameObject class, but we can now let the GameObject class implement this interface
as well, by defining the class as follows:
class GameObject : IGameLoopObject
{
// member variables, methods, and properties
}
Search WWH ::




Custom Search