Chapter 9. Finite State Machines

A finite state machine is an abstract machine that can exist in one of several different and predefined states. A finite state machine also can define a set of conditions that determine when the state should change. The actual state determines how the state machine behaves.

Finite state machines date back to the earliest days of computer game programming. For example, the ghosts in Pac Man are finite state machines. They can roam freely, chase the player, or evade the player. In each state they behave differently, and their transitions are determined by the player’s actions. For example, if the player eats a power pill, the ghosts’ state might change from chasing to evading. We’ll come back to this example in the next section.

Although finite state machines have been around for a long time, they are still quite common and useful in modern games. The fact that they are relatively easy to understand, implement, and debug contributes to their frequent use in game development. In this chapter, we discuss the fundamentals of finite state machines and show you how to implement them.

Basic State Machine Model

The diagram in Figure 9-1 illustrates how you can model a simple finite state machine.

Generic finite state machine diagram

Figure 9-1. Generic finite state machine diagram

In Figure 9-1, each potential state is illustrated with a circle, and there are four possible states {Si, S1

Get AI for Game Developers now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.