r/codereview • • 22d ago

Made a small easy to use State Machine.

Wanted a state machine tool for myself in various projects but also for other developers, been having fun with it and learning more C# concepts.

Features

  • Enum-keyed states, using a non boxing key internally, the underlying value and the enum's type are packed into a struct, so no enum ever gets boxed
  • Nested substates, each with it's own events and it's own current substate
  • Predicate transitions that are safe to poll every frame (optional)
  • Optional context objects passed to handlers on enter, update and exit; sealed record types with value equality and built in deconstruction, up to 10 values
  • Per state Enabled flag and per substate update propagation
  • IndependentUpdate to tick a specific substate by a path of enum keys, mixing enum types freely across levels
  • Transitions requested from inside callbacks are queued and run after the current pass, so handlers can request transitions without breaking the machine
  • TryCreateState, TryGetState and StartState return false instead of throwing for common mistakes

Here's a quick use guide I made to demonstrate usage:

using SMachine;

public enum States { Idle, Combat }
public enum CombatSubs { Melee }

private string Name;
private int HeroAttack;

public void Initialize()
{
    var machine = new StateMachine();

    // States belong to the machine
    State idle = machine.CreateState(States.Idle);
    State combat = machine.CreateState(States.Combat);

    // Substates belong to a state
    SubState melee = combat.CreateState(CombatSubs.Melee);

    // Create a context object to pass to your handlers (optional)
    var ctx = new Context<string, int>("Hero", 10);

    // Subscribe to the events
    combat.OnEnter += () => Console.WriteLine("Combat has begun!");

    melee.OnEnterContext += (ctx) => {

        // I recommend using pattern matching for ease of use and safety
        if (ctx is Context<string, int>(string name, int attack))
        {
            Name = name;
            HeroAttack = attack;
        }
    };

    // Start your states
    machine.StartState(States.Combat); // This fires OnEnter
    combat.StartState(CombatSubs.Melee, ctx); // This fires OnEnterContext

    // Subscribe to the OnUpdateContext event
    melee.OnUpdateContext += HeroAttack;

    // Call Update on our machine for Combat state to update, then Melee
    machine.Update(ctx);
}

public void HeroAttack(BaseContext ctx)
{
    // We can also access context directly after casting
    var typed = (Context<string, int>)ctx;
    Console.WriteLine($"{typed.Data1} hits Goblin for {typed.Data2} damage!");
}

There are other features like Update Propagation, Independent Updates, and the Context type itself. I explain it all in detail over on my GitHub.

Let me know what you guys think, have any suggestions or just want to tell me I suck at programming (please don't be mean).

3 Upvotes

6 comments sorted by

2

u/Exotic-Ninja5489 19d ago

making `StartState` return false instead of throwing for common mistakes might bite you in production tbh. silent failures in state machines are usually a nightmare to debug when a transition just quietly doesnt happen.

1

u/Boarlock98 19d ago

Good point. I was actually wondering that myself if I should throw there or pre-emptively transition for the user. I remember during the documentation that it taught to throw when the method has no way to proceed forward. For this I kind of interpreted that as something which is programming error like feeding a state from another machine into this machine, versus sending a call at the wrong time like StartState when you meant TransitionState. I see why being explicit about operations is ideal though that way the user can correct the behavior instead of it silently not working.

1

u/LaurenceDarabica 20d ago

What's wrong with Stateless ?

1

u/Boarlock98 20d ago

Nothing, I wanted to make my own. Also if anyone wanted a lightweight framework that does just the essentials, they can use this library.

1

u/Angelvin_Pinheiro 19d ago

Wait, in your example `combat.CreateState(CombatSubs.Melee)` returns a `SubState`, can a `SubState` also have its own substates or is the hierarchy strictly two levels deep?

1

u/Boarlock98 19d ago edited 19d ago

Yes SubState has SubState for it's children. SubState and State are the same (SubState inherits State with essentially no overrides). The difference between the two is Update Propagation property which controls the Update calls forwarded to that SubStates children, and Parent property which is the owner of that SubStates (State or SubState).

The hierarchy can be as deep as you need but there are only 18 overloads for the Independent Update method. Which means you can only go 19 states deep for independent update (though Update continues deeper as long as their update propagation is true).