Build a light switch and even an enemy AI!

The finite state machine (FSM) is one of the most flexible and widely used object-oriented design patterns in technological engineering. A FSM consists of a collection of states for a given model that has “transitions” which allow one state to switch to another based off of predefined conditions. Despite its simple idea, FSMs are so adaptive that they apply to an incredibly broad range of implementations including:

  • Adaptive UI Design — If a user’s behavior can be mapped onto a finite state machine, then the risk of a user stepping outside of program bounds and causing an error is minimized.
  • Markov Chains — Assuming a probabilistic framework and a finite set of states, a FSM can be used to model a Markov Chain.
  • Testing Network Protocols — A network protocol such as TCP can be modeled using a FSM in order to verify flow of traffic and communication. A FSM usually cannot be used for production in this scenario because they are inherently limited in data storage capabilities.
  • Common Applications — Traffic lights, vending machines and elevators are state based in nature and so make for excellent applications of a FSM.

In this article, we will explore two different examples of a finite state machine written in Go. After reading this article you should have a good idea of what a FSM is, how to implement one by hand as well as the pros and cons. The examples we will cover include:

  1. A simple example to model a light switch.
  2. An enemy AI using a map.
  3. Key takeaways

Let’s get started!

#golang #tutorial #programming

Finite State Machines in Go
9.40 GEEK