What is State Machine?

  1. A system with a limited number of defined 'states'.
  2. Which can only be in one 'state' at a time.
  3. That has well defined rules to 'transition' between states.

A State Machine Example: Traffic Light

traffic light

  1. How many states does a traffic light have?
  2. What names should they have?
  3. Can it be in more than one state at a time?
  4. What are the rules for transitioning between states?

image by katerha

Traffic Light State Transition Diagram


[G] -> [Y] -> [R]
 ^             |
 |_____________/

What if a "left turn only" green arrow existed as well?

A State Machine Example: Simon Game

An animated overview of the simon game

  1. How many states? What are their names?
  2. Can it be in more than one state at a time?
  3. What are the rules for transitioning between states?

State Transition Diagram: Simon

[G] <-> [Y] 
 ^ \   / ^
 |   X   |
 |  / \  |
 v       v
[R] <-> [B]

State Machine Example: GUI Button

States:

  1. Enabled
  2. Disabled
  3. Pressed
  4. Active

State Machine Example: GUI Button Transitions

Transitions:

We may also need a state transition action: "when the button enters the 'active' state, send a 'click' event and then enter the 'Enabled' state"

Why use a state machine?

  1. Clarity
  2. Predictability
  3. Fail-fast debugging

State of the State 1

The term "state" has several overlapping meanings.

State of the State 2

The term "state machine" has several technical variants as well.

https://en.wikipedia.org/wiki/Finite-state_machine

How to implement a state machine?

let states = {
  "green": {canChangeTo: ["yellow"]},
  "yellow": {canChangeTo: ["red"]},
  "red": {canChangeTo: ["green"]}
}

let currentState = "green";

function enterState(newState) {
  let validTransitions = states[currentState].canChangeTo;
  if (validTransitions.includes(newState)) {
    currentState = newState;
  } else {
    throw "Invalid state transition attempted - from " + currentState + " to " + newState;
  }
}

 Previous

Outline

[menu]

/