Datasheet

THE GAME LOOP 45
game engine must determine if there have been any collisions between
the graphics elements and calculate their resulting status, such as their
visibility (Have they moved off screen? Is one asteroid overlapping the
others? Has a collision broken an asteroid into fragments?), and their
changes in shape or color. The game engine also calculates status
values, such as the player’s score or the ammunition available.
The screen is updated according to the new state calculated by the
game engine.
Having calculated the internal game state to reflect the new positions
and status of each game object, the game engine prepares the next
image to display on the screen to reflect those changes. Once the new
frame is prepared, it is drawn to the screen. Each time the screen is
updated, the new image displayed is known as a frame. The number
of frames written to the screen per second is known as the frame rate.
The higher the number of frames per second (fps), the smoother the
graphics transitions appear, so a desirable frame rate is a high one
in games with rapidly changing graphics. However, the exact figure
depends on the game in question, affected by factors such as the
amount of processing required to generate the next frame and the
genre of game, since some games, such as turn-based games, do not
require a high frame rate.
The game’s audio (background music and sound effects) are synchro-
nized with the game state.
For example, the sound of an explosion is played if the latest game
update calculated that a collision occurred.
Figure 2.1 shows this graphically, while in pseudocode, a basic game
loop can be expressed as follows:
while ( game is running )
{
calculate time elapsed and retrieve user input
update game internals
update graphics (prepare frame, draw frame)
synchronize sound
}
Note that a constantly running game loop is not necessary in every
game. While it is needed for a game with frequently changing graphics
in order to update the display, some games are more like typical event-
driven applications. A turn-based game, like chess, may not need a game
loop to run all the time, but can be driven by user input. The loop starts
running when a turn is taken, to update the graphics to reflect the move,
and calculate the AI’s response, then returns to waiting on an event to
indicate the user’s next move or other input, such as deciding to quit the
game.