DEV Community

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

Collapse
 
yjdoc2 profile image
YJDoc2

I'm not sure if this would be a good way, but I will try anyways :

Think of game of snakes/chutes and ladders - and that is a state machine. You roll a dice and whatever comes on top, you move your piece by that much number. The piece will move from one square, to some other square depending on what was on that dice. Now sometimes, one can change the square without a dice, just because they are on that square, for example when the encounter snake/chute or when they encounter a ladder.

Now Imagine starting to watch a game being played some time after it has started. One of the pieces is on square number 11, but we have no way of telling how it got there. Maybe player rolled a five then a six, or maybe they rolled a five, another five and then a one, or maybe they are there because a snake/chute on 21 got them back to 6 and then they rolled 5. But in the game it doesn't matter how they got there, what matter, is that players have fun.... and also what players roll next on the dice, as the next movement depends only on that.

State machines are like that, too. A machine's state (position of piece) changes depending only on what is the next input (what comes next on dice), and there may be multiple ways of reaching a state (How it reached square 11), but which way it used does not affect its next transition (move). There can be ways to change state just because one is in a particular state, using epsilon transitions (one can move squares because they encountered snake/chute or ladder, without rolling dice). And in the end important thing is that players have fun (I think it is important 😄)

I think it would be possible to explain using hopscotch as it literally has jumping from one state to another, but my knowledge of that is non-existent 😅

Hope this is useful !