I made a General Purpose State Machine (GPSM)

Hi guys! :waving_hand:

I made yet another state machine plugin: general purpose state machine (GPSM).

The existing state machines I saw were more or less improvised, bloated or had no tests (I know probably there is good ones out there too). So I wrote some tests for a minimal state machine.

For this one I tried to keep it as simple as possible. That is also why it is not based on Nodes, but on scripts. Or rather just one single script, because GPSM lives in a single file.

The concept is simple: one expresses states and transitions and one can attach to Godot signals for each state and transition. When one triggers a transition it is only taken if the machine’s current state is the transition’s state of origin. Otherwise the transition fails.

For each state there is 4 signals and for each transition there is 2 signals to attach to. That’s all! Ah yes, and the machine allows to address states and transitions with text aliases.

For creating a machine with 5 states and 3 transitions this much code is needed:

  GPSM.new_machine('MY_MACHINE')
	var sm: GPSM = GPSM.get_machine('MY_MACHINE')
	var A: GPSM.State = sm.new_state()
	var B: GPSM.State = sm.new_state('NAMED STATE')
	sm.new_state()
	sm.new_state()
	var C: GPSM.State = sm.new_state()
	var T0: GPSM.Transition = sm.new_transition(A, C)
	var T1: GPSM.Transition = sm.new_transition(B, A, 'NAMED TRANSITION')
	var T2: GPSM.Transition = sm.new_transition(sm.state_dict\['NAMED STATE'\], C)

For triggering a transition:

  var transition: GPSM.Transition = sm.transition_dict\['NAMED TRANSITION'\]
  if transition:
    transition.trigger()

Looking forward to hear what you guys think.

Cheers! :four_leaf_clover:

The code is also on Github and also includes a demo scene:

1 Like