views:

573

answers:

4

I am trying to build a board game ... And looks like it has to be implemented using a state machine..

I know of the State pattern from GoF, but I am sure there must be other ways to implement state machine. Please let me know.. if you know of any articles or books that contains details about different implementation (trade off of each of them), please direct me.. thanks

A: 

(Flagged for deletion)

duffymo
I am using c# but example in any other language would be fine... and I am not looking for framework... I want to know in general about the different designs and trade-offs of state machine implementation
StackUnderflow
+2  A: 

Hi

Here's a very simple FSM implementation:

public delegate void ProcessEvent<TEvent>(TEvent ev);

public abstract class StateMachine<TEvent>
{
    private ProcessEvent<TEvent> state;

    protected ProcessEvent<TEvent> State
    {
        get { return this.state; }
        set { this.state = value; }
    }

    public void ProcessEvent(TEvent ev)
    {
        this.state(ev);
    }
}

You would use it as follows:

public class MyFsm : StateMachine<byte>
{
    public MyFsm()
    {
        this.State = this.Started;
    }

    private void Started(byte ev)
    {
        Console.WriteLine(ev);

        if (ev == 255)
        {
            this.State = this.Stopped;
        }
    }

    private void Stopped(byte ev) { }
}

class Program
{
    static void Main(string[] args)
    {
        MyFsm fsm = new MyFsm();
        fsm.ProcessEvent((byte) 0);
        fsm.ProcessEvent((byte) 255);
        fsm.ProcessEvent((byte) 0);
    }
}
Andreas Huber
I assume that's C#? it would help to clarify which language (doesn't quite look like Java or C++)
Jason S
Yes, this is C#.
Bryan Anderson
+3  A: 

Check out Ragel.

Hank Gay
+1  A: 

We've used Harel's statecharts (similar/equivalent to state machines but somewhat easier to think about), there's a good book called Practical Statecharts in C/C++.

Jason S