Rafael Maia
1 supporter
What is a State Machine?

What is a State Machine?

Jun 12, 2024

A state machine describes a system that has states. In computer science, a state is simply a set of related data at one time. Between these states, we have transitions that determine what must happen for the system to change to new states. Each state has transitions in and out of other states. A state machine gives you a general abstract overview of what its states and transitions are.

A state machine can be in any one of its states at one time. Those states together represent the behavior of the object, or state machine. Each individual state has its own logic and manages its own data. By separating the logic of these states, we can build more scalable code and avoid monolithic codebases.

For instance, imagine a character in a game that can duck, stand, jump, and dive. If we don't press anything, the character is probably just standing still, doing nothing. That's a state. Then, once we press the right button, we have a transition, and the character can duck. Now that the character is ducking, that's another state of the character. Once we release that button, the character goes back to its standing state. That's a transition. The same happens for when it is jumping or diving.

Here's an image to illustrate this:

Image by Robert Nystrom, in his book Game Programming Patterns.

So, if an object in your program needs to have different sets of logics depending on what state it is in, it's a good idea to implement a state machine and think about the transitions that need to take place for the object to go from one state to another.

Enjoy this post?

Buy Rafael Maia a coffee

More from Rafael Maia