Game Development Reference
In-Depth Information
An
introduction
to
Finite
State
Machines
A common strategy in game play programming (and computer science in general) is
to model a system in terms of discrete objects and their interactions with one another.
To do this requires us to understand what the participants are in a system, how they
operate in different scenarios, and how they change states.
The Finite State Machine ( FSM ) is one such technique. With this, the idea is to mod-
el the behavior of the object in a number of code blocks. Inside each one, you put the
specific code for that block that makes it unique. You also determine what scenarios
cause an object to switch from one block (state) to another. Because each state is
an encapsulation, it makes your code extensible and maintainable (which is a great
thing!).
Implementing an FSM in a game
While there are many ways of programming an FSM, we will commonly encounter two
strategies as game programmers on our e-learning example. Each one has its own
unique structural components, benefits, and drawbacks.
The switch case FSM
In this form, we require three components:
• An enumeration to list the states: Each individual element in the enumerated
type corresponds to a single state in the FSM model. For example, an FSM
with three states could be implemented in the enumeration eMyState as
shown in the following code:
public enum eMyState {
STATE_INVALD = -1, // an error state
which can be used to
encode the logic for processing an
error condition
STATE_A = 0, // an arbitrary state in an
Search WWH ::




Custom Search