State Machine Implementations

喜夏-厌秋 提交于 2019-12-22 08:28:53

问题


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


回答1:


Check out Ragel.




回答2:


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++.




回答3:


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);
    }
}



回答4:


Finite State Machines provide the best platform to implement games which are all events driven.

Since your goal is to build the state machine you can use an existing framework and than all you need is to add your events extractors and actions.

One example framework can be seen at:

http://www.StateSoft.org



来源:https://stackoverflow.com/questions/398458/state-machine-implementations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!