DEV Community

Discussion on: Explain a State Machine Like I'm Five

Collapse
 
kallmanation profile image
Nathan Kallman

How about a stop light. The lights change from state to another; always following the same rules of when to change. But let's do an example:

There's a Red light, a Yellow light, and a Green light where a big road and a little road cross.

We want the big road to always have a Green light so everyone can keep going. Except sometimes when a car stops on the little road we'll want to change the light so they can go too. And we don't want someone to have to stand by the intersection all day to change the lights so we'll use a machine; a State Machine!

Let's first think about the different states a stop light can be in. We don't want both lights to be Green! The only safe ones are:

  1. Green/Red
  2. Yellow/Red
  3. Red/Red
  4. Red/Green
  5. Red/Yellow

These are the states for our machine. But we aren't done, we need to decide when the light should change. Remember we wanted the big road to usually have a Green light; so let's start with that light Green and the other one Red; Green/Red (the first state).

The only time we want to change the light from Green/Red is when a car comes on the little road. When that happens we'll turn the big roads light Yellow to tell those people to slow down by changing to the Yellow/Red state.

After 5 seconds we'll change all the lights to Red to make sure everyone is safe; Red/Red. After another second we'll turn the little roads light Green to let them across; Red/Green.

After 10 seconds they've probably made it across, so let's start changing the light back by making it Red/Yellow. But wait; there's a little problem, do you see it? We need to change the light to Red/Red, but the rule for our Red/Red state is to go to Red/Green after 1 second. If we did that then the big road wouldn't get their turn to go! To remember whose turn is next we need a different state than our first Red/Red; both states have the same lights turned on (Red and Red) but they have a different rule: The first goes to Red/Green and the second goes to Green/Red after 1 second.

Here's a little picture of our "State Machine":
Stop Light State Machine Diagram