[C #] Implementation of a simple finite state machine.

1 minute read

This is the first post in a long time.

Implementation

It is an implementation of a finite state machine.

StateMachine.cs


/// <summary>
///Finite state machine(FSM), where T : class
/// </summary>
public class StateMachine<T> 
    where T : class
{
    private T m_Owner;
    private State<T> m_CurrentState;
    public State<T> currentState { get {return m_CurrentState;} set{ m_CurrentState = value;} }
    private State<T> m_PreviousState;
    public State<T> previousState { get {return m_PreviousState;} set{ m_PreviousState = value;} }
    private State<T> m_GlobalState;
    public State<T> globalState { get {return m_GlobalState;} set{ m_GlobalState = value;} }
    /// <summary>
    ///constructor
    /// </summary>
    public StateMachine(T owner){
        m_Owner = owner;
        m_CurrentState = new NullState<T>();
        m_PreviousState = new NullState<T>();
        m_GlobalState = new NullState<T>();
    }
    /// <summary>
    ///Perform the current state
    /// </summary>
    public void Update(){
        m_GlobalState.Execute(m_Owner);
        m_CurrentState.Execute(m_Owner);
    }
    /// <summary>
    ///Change the current State
    /// </summary>
    public void ChangeState(State<T> newState){
        // Assert(newState != null);
        m_PreviousState = m_CurrentState;
        m_CurrentState.Exit(m_Owner);
        m_CurrentState = newState;
        m_CurrentState.Enter(m_Owner);
    }

    /// <summary>
    ///Change to the previous State
    /// </summary>
    public void RevertToPreviousState(){
        ChangeState(m_PreviousState);
    }
}
    

It is an implementation of the state.

State.cs


public interface State<T>
    where T : class
{
    /// <summary>
    ///Called when this State is reached
    /// </summary>
    void Enter(T t);
    /// <summary>
    ///Called all the time during this State
    /// </summary>
    void Execute(T t);
    /// <summary>
    ///Called when changing from this State
    /// </summary>
    void Exit(T t);
}

It is a null state implementation.

NullState.cs


/// <summary>
///Class to avoid null
/// </summary>
public class NullState<T>: State<T> 
    where T : class
{
    public void Enter(T t){}
    public void Execute(T t){}
    public void Exit(T t){}
}

how to use

Main.cs


void main(){
    //Class that manages transitions
    MyClass myClass = new MyClass();
    //State machine declaration
    StateMachine<MyClass> stateMachine = new StateMachine<MyClass>(myClass);
    //A class that implements the state interface
    State<MyClass> myState = new MyState();
    //Change current state
    stateMachine.ChangeState(myState);
    //Perform current state
    stateMachine.Update();
}