Game Development Reference
In-Depth Information
Game State
The overall state of the game is controlled by GameState (in GameState.cs),
which is why it's the largest file in the game. It's a state machine, but because
the main menu and pause state have so little behavior, almost all of the code in
GameState is for controlling the overall gameplay. Because so much of the code
is for one particular state, I did not use the state design pattern (as in Chapter 9 ,
Artificial Intelligence ”). But if a particular game has a lot of different states (such
as different game modes, for instance), it probably would be a good idea to refact-
or this to use the design pattern instead.
Anything related to the overall state of the game, such as the amount of money, the
health, the time until the next wave, and so on, are also stored in GameState . So
the majority of the member variables in GameState are very game specific, but
there are some that aren't. One is the linked list of all of the active game objects
in the world. All new game objects must go through the SpawnGameObject
function in GameState , as that's what adds it to the game world. Then, in Up-
dateGameplay , all of the game objects are updated provided that the game is
not paused.
There are a couple of wrinkles worth mentioning in UpdateGameplay . First of
all, it doesn't actually iterate on the game object linked list, but on a copy of the
game object linked list. This is to allow for the fact that some game objects might
need to remove game objects (including themselves) during the update. In C#, the
foreach does not allow for modification of the container during the loop, which
is why the copy is made. Although this may seem very inefficient, keep in mind
that classes are always passed by reference in C#. So copying the list is just doing
a shallow copy of pointer data, which isn't really that computationally expensive.
The other notable code in this function is that the delta time that UpdateGame-
play receives isnotalways the delta time that ispassed toall ofthe game objects.
This is what allows the player to change the speed of the game using the +/- keys.
GameState also has an instance of the Camera class that it keeps track of.
Another important member variable in this class is the UI stack, which is a stack
of all the currently active user interface screens. The UI system will be discussed
in further detail later in this chapter.
Search WWH ::




Custom Search