• Recent Tutorials

  • Tripping The Class Fantastic: State Machines

    State Machines

    This is not going to be a complete history of state machines and it certainly won't be a definitive guide to them... what I hope it will be though is a primer for anyone who isn't familiar with the concept.

    So what is a state machine?

    A finite state machine (FSM or state machine for short) is a simple construct where your software is in one state at any given time (the current state). Flow is achieved by moving from one state to another (transitioning) with such movements being triggered by certain events.

    Isn't all software like this?

    Not exactly.

    If you take Windows as an example, the bulk of applications are made up of chunks of code that get fired up in response to simple events. User clicks buttons, user changes text (yes, this is a very simple view, but it's also one that most people should be familiar with).

    Now consider something a little different. Lets use the card vendor from my previous article. It's firmware consists of a number of states. It's initialising, it's waiting for a vend signal, it's vending, it's returning the vend mechanism to the home position, it's waiting for a vend signal, it's vending, it's jammed!

    Once it enters any of these states, it will perform a required action and move to the next state or it will wait in the current state until a set of conditions exist, at which point it will move onto another state.

    So what are the uses of state machines?

    They are literally everywhere... if it's electronic and digital, there is a good chance it has a state machine in it.

    Software wise, they sit at the heart of hardware interfacing, parsing communications protocols, compilers and of course a subject close to our hearts... games.

    You use them when you make a cup of coffee... is the kettle full? No, fill it. Yes, is it turned on? No, turn it on. Yes, is the water boiling... and so on.

    Comments 3 Comments
    1. Ñuño Martínez's Avatar
      Ñuño Martínez -
      Just did a very fast reading (titles and some of the code, not much more). Looks very interesting.

      I did my own state-machine library translating the one described in"Programming Game AI by Example". Your approach seems slightly different. I'll tell you once I read your tutorial in-deep and compare both ways.
    1. AthenaOfDelphi's Avatar
      AthenaOfDelphi -
      If anyone has downloaded the attachment, the file classBaseStateMachine.pas was missing. Sorry about that, thanks to d.spinetti for pointing out my mistake.
    1. Ñuño Martínez's Avatar
      Ñuño Martínez -
      Read. Your implementation is way different than the one described in"Programming Game AI by Example" but it's a nice approach.