Finite State Machine

A Finite State Machine (FSM) is a very simple, easy to implement, low cost form of AI. 

Lets use the example of a game where your AI is a dragon and he needs to guard a treasure.  Our dragon can see things, and can smell things, but is a little hard of hearing.  The human players, the knights in shinning armor, can walk around freely as long as they don’t knock over any rocks that might draw his attention (visually), or get too close to him when he’s sleeping because he would then smell them.

An example of a FSM would be:

bulletIf our dragon smells the player, wake up (open eyes)
bulletIf our dragon sees the player, attack
bulletIf our dragon does not see or smell the player, go to sleep (close eyes)

Coding this is as simple as using if / else if / else statements and having variables to keep track of the current states of the dragon.  A boolean variable that is true when it smells the player, another boolean variable that is true if it sees the player.

If you coded the above three and then decided to add in more, you can simply add in more states.  Say we wanted to add in these two states:

bulletIf you smell the player and the time you have been out searching is less than 20 game time cycles, go search for him/continue the search.
bulletIf you smell the player and can’t find him within 20 game time cycles, go back to your treasure.

Adding in the code would be simple too.  Add in a few more else if statements and add an integer variable that will keep track of the time that the dragon has been searching for the player.  It is very important to keep good track of what each state does, how to get into each state, and how to get out of the state.  This is important so that you can enter and exit all your states and have all your variables change properly.

Drawbacks

A common problem is adding in a state and some variables, but then you forget to reset a variable or two in a previous state because when you coded that previous state, you didn’t have those variables.

Another drawback to this architecture is that you need to think up all the different possible states that your AI player can be in.  For our simple example, it isn’t too hard to do this, but for a larger game, there might be well over fifty or a hundred different states your AI can be in.  This means you need to program every single state into the code.  Then going back to the first drawback mentioned, you might have a lot of work on your hands to just add in one simple state.

 

|<    <    >    >|