Finite-state machine

Started by
4 comments, last by bd36 12 years ago
what are some ways of implementing a Finite-state machine?

i know one way is to have an enum of states and a bunch of switch-case statements.
Advertisement
An enum, as described, is often the simplest and best solutions. For complicated state machines, where each state has a lots of unshared data (or possibly other, internal, state machines), they can be modelled as objects, sometimes with a simple inheritance hierarchy.

Sometimes the state machine isn't made explicit and is just the interaction between a couple of key variables (e.g. state X is when B = true and C < 5, state Y is B = false and C < 42, ...). Making the presence of distinct states explicit can make it clear the steps that are going on, and the transitions that should be considered valid, even if the state can be inferred from other data that must be maintained anyway.
On past projects I've been on, I've found it easy to maintain to do exactly as you describe, use a switch/case statement inside a statemachine class that simply calls a series of virtual methods that call a OnWhateverEvent() that many scripters are used to working with. Then each AI inherits and overrides the virtual method and calls the base methods as need be.

I've found doing things "directly" like following a linear state machine chart cause maintenance issues later on, especially if you eventually have to give your code to another programmer.
There was a rather complex social AI I helped with a few years back. It was essentially a state machine of state machines. It was complex enough and dynamic enough that a traditional state machine couldn't handle it. Ultimately we ended up using the Visitor Pattern for the parent machine.

For an indirect state machine, or a 'programmable' state machine where the machine itself doesn't know the states that machine-users will follow, the visitor pattern can be very useful. It is a relatively complex pattern (one of the most complex in the GoF book), but still very useful in this case.
It's possible to use mappings to associate a state and symbolic input with the consequent state. A transition method would accept a symbolic input and return the next state based on the current state and the given symbolic input. This simple implementation performs no conditional logic. That would be implemented elsewhere.

It is like a switch statement except the focus is on data rather than logic and both accomplish the same thing, but there are subtle style and layout differences.
I was looking to implement my first state machine in the game that I am working on now. I am not using SDL but found the concepts and explanations in this article very helpful and it works for what I needed.

http://lazyfoo.net/articles/article06/index.php

This topic is closed to new replies.

Advertisement