Finite State Machines

Finite State Machines (FSMs) are a tool that should probably be in every programmer's and engineer's toolbox. Within the context of a Visual Novel they are particularly useful for capturing the behaviour of non-player characters (NPCs), events that can happen in a certain sequence or with variations, and the logic of machinery and puzzles. Any time that you find yourself with a bunch of flags that all relate to the same thing, a finite state machine can be a cleaner solution.

What is a finite state machine?

In very simple terms (there is a lot of academical research on the topic) a finite state machine can be considered a box with a number of inputs, a number of outputs, and some internal state that controls how the inputs affect the outputs. Critically the number of internal states is finite, and can easily be represented with a simple integer.
See Wikipedia: Finite State Machine 

It is easier to understand with a simple example.

Combination lock

A simple briefcase or padlock has a number of dials for entering a combination, and a button or similar to try to open it. To open the case the player must:

  1. Enter the correct combination
  2. Open the case

To lock it back up there are two options:

  1. Close it and then scramble the combination
  2. Scramble the combination then close it
Importantly if it is closed and the combination isn't scrambled anyone can open it. Also if it is open and the combination is scrambled then when it is closed it is also locked.

Inputs and outputs

The inputs are easy to identify:

And there is a single output:

States

Four states are needed to describe the operation of the lock. I've numbered each of them:

0:Locked
The case is closed and the combination is wrong
1:Closed
The case is closed but the combination is correct
2:Open
The case is open and the combination is correct
3:Scrambled
The case is open but the combination is wrong

Transitions

Changing from one state to another is called a transition. Having identified all the input, outputs, and states it is possible to identify and draw all the important transitions.

Combination lock state diagram

To keep the diagram simple input that do nothing (like trying to open it while it is already open) are not shown. These don't change the state, and are not transitions.

Diagrams are useful for having an overview of the operation and documentation. I've used a Freeware tool called yEd  to draw these diagrams, as it has a convenient Scalable Vector Graphics (SVG) output that suits web browsers but other tools are available. Something that allows you to move the state boxes around and have them remain connected is very useful. There are a few standards for how to draw state diagrams, and specific editors that support them. I chose not to use these here as they offer formal features that are not needed for these simple examples, and it would add something else to explain.