Aug. 7, 2011

A finite-state machine is an algorithmic structure which is frequently useful in video games. A finite-state machine can be used to simulate any game entity which has a set of discrete states which it changes between, and which looks different and/or exhibits different behaviour in each of those states. Here are some examples:

  • A non-player character which wanders around and then starts chasing the player once they come in range.
  • A door which switches between closed, opening (animated), and open states.
  • A spacecraft under player control which has an proximity-triggered docking procedure.

Public domain image of a finite-state machine from Wikipedia

Many video game entities can be most easily modelled in this way. In jsGameSoup it is now very easy to create state machines like this. Simply include "statemachine.js" in your HTML file:

<script src="jsGameSoup/js/statemachine.js"></script>

Then call the statemachine() function on an entity inside it's constructur:

function MyEntity() {
    statemachine(this);
    ...
}

After that your entity will have a new method set_state(state) which switches it between different arbitrary states. These states are completely up to you. You can define different behaviours, events, and visual representations by creating multiple versions of jsGameSoup's normal expected methods. For example, let's say the entity above has a state "wandering" and a state "seeking" when it is moving towards the player. In this case we would define two different sets of methods:

/****** Update and draw this entity in the wandering state. ******/

this.wandering_update = function() {
    // update the entity in "wandering" mode
    ...
}

this.wandering_draw = function() {
    // draw the entity in "wandering" mode
    ...
}

/****** Update and draw this entity in the seeking state. ******/

this.seeking_update = function() {
    // update the entity in "seeking" mode
    ...
}

this.seeking_draw = function() {
    // draw the entity in "seeking" mode
    ...
}

When you want to put the entity into a particular state, you call set_state(state), for example in the init() method of the entity to put it into a certain state from the start:

this.init = function() {
    this.set_state("wandering");
}

Here is an example of a jsGameSoup entity class which switches between a "chill" and an "antsy" state. View source to see how it works.

Hopefully this will help you write games and get them infront of players more quickly.

Screenshot of an old game

Need software development advice? Book a call with me.