Finite State Machine

A class representing a Finite State Machine. It consists of the current state and transitions associated with given states, which allow the state machine to transition from one state to another, based on user-provided conditions. Finite State Machine is also a state itself (via inheritance) to allow for easy hierarchisation.

Important Methods

Constructors

There are two different constructors for this class:
  1. The first one needs a list of transitions, the initial state, and the state machine’s name.

  2. The second one needs a map/dictionary of transition functions associated with states, the initial state and the state machine’s name. Transition functions should return the state to transition to, or null if current state does not change.

    This constructor allows users to create a bit more flexible state machine, but it is not possible to initialize state machine with it from config tools.

  • C++

  • C#

std::vector<grail::fsm::FiniteStateMachine::Transition> transitions
{
  { oneState, anotherState, condition },
  { anotherState, yetAnotherState, [](){ return true; } },
  //etc.
};
grail::fsm::FiniteStateMachine firstFsm{transitions, oneState, "first fsm"};

std::map<std::shared_ptr<grail::fsm::State>, std::function<std::shared_ptr<grail::fsm::State>()>> transitionFunctions
{
  { oneState, [&condition]() { return condition ? anotherState : nullptr; } },
  { anotherState, []() { return yetAnotherState; } },
  //etc.
};
grail::fsm::FiniteStateMachine secondFsm{transitionFunctions, oneState, "second fsm"};
List<(State sourceState, State destinationState, Func<bool>)> transitions = new()
{
  (oneState, anotherState, condition),
  (anotherState, yetAnotherState, () => true),
  //etc.
};
Grail.FSM.FiniteStateMachine firstFsm = new(transitions, oneState, "first fsm");

Dictionary<State, Func<State>> transitionFunctions = new()
{
  { oneState, () => condition ? anotherState : null },
  { anotherState, () => yetAnotherState },
  //etc.
};
Grail.FSM.FiniteStateMachine secondFsm = new(transitionFunctions, oneState, "second fsm");

Enter

Overriden state’s Enter method. Calls Enter on current state.

Update

Overriden state’s Update method. First processes transitions, then calls Update on current state.