A Different Path

Learn to build a state machine to embody the rules.

Functional state machine

You might think we could make decisions about the application stages, stage transitions, and events with conditional logic. You would be right, but the costs would be high. The number of nested if statements necessary to do the job would lead to a snarl of code paths. We would face real readability and maintainability problems.

Therefore, we’re going to choose a different direction. We’ll implement our own purely functional state machine to handle all the stages that Islands will go through in the course of a full game. It’s going to make decisions for the application about which actions to allow and which to deny at a given stage. It will manage transitions from one stage to the next and will help the game enforce the rules.

By implementing our own state machine, we’ll keep the logic for managing the state separate from the rest of the game logic. This separation of concerns will keep our code clean, readable, and maintainable.

Before we go any further, let’s get a better understanding of state machines in general and take a look at an example of a problem ideal for a state machine to solve.

State machines

State machines are fundamental to computation. A finite state machine is a form of an abstract machine. It defines a finite number of states a system can be in, as well as any events in the system that can trigger transitions between those states. Any time we need to model a complex process that proceeds through a number of states—especially ones that might loop back to earlier states—we should think about reaching for a finite state machine.

Get hands-on with 1200+ tech skills courses.