
Are you a C# developer tired of tangled if-else chains and convoluted switch statements? Meet FSM_API, a high-performance, open-source library designed to bring clarity and control to your application logic using Finite State Machines (FSMs). Built for pure C#, it's ready to streamline complex behaviors in anything from backend services and desktop apps to games and simulations.
FSM_API takes the classic FSM pattern and supercharges it with modern features:
Decoupled Logic: The FSM logic is cleanly separated from your application's data. This means you define a single "blueprint" for a behavior and can use it to control many different objects (or "contexts") independently.
Runtime Safety: A robust Cascading Degradation System catches exceptions within your FSM's actions and conditions. Instead of crashing your application, it can gracefully shut down a problematic instance, ensuring stability.
Flexible Updates: You have granular control over when your FSMs "tick" or process their logic. You can choose to update an FSM every frame, at a fixed rate, or only when triggered by a specific event.
A Glance at the Code: Making a Light Switch FSM
The library uses a fluent, declarative API that makes FSM definitions highly readable. This example shows how to define a simple LightSwitch FSM that transitions between On and Off states.
// 1. Define a simple context for your data modelpublic class LightSwitch : IStateContext
{
public bool IsOn = false;
public bool IsValid => true; // FSM API will not operate on this if IsValid is false.
public string Name { get; set; } = "KitchenLight";
}
// 2. Define and build your FSM blueprint
FSM_API.Create.CreateFiniteStateMachine("LightSwitchFSM", processRate: 1, processingGroup: "MainLoop")
.State("Off",
onEnter: (ctx) => { if (ctx is LightSwitch l) l.IsOn = false; },
onUpdate: null,
onExit: null)
.State("On",
onEnter: (ctx) => { if (ctx is LightSwitch l) l.IsOn = true; },
onUpdate: null,
onExit: null)
.WithInitialState("Off") // Must set an initial state
.Transition("Off", "On", (ctx) => ((LightSwitch)ctx).IsOn)
.Transition("On", "Off", (ctx) => !((LightSwitch)ctx).IsOn)
.BuildDefinition();
// 3. Create a live instance for your contextvar kitchenLight = new LightSwitch();
var handle = FSM_API.Create.CreateInstance("LightSwitchFSM", kitchenLight, "MainLoop");
// 4. Tick the FSM from your application's main loop
FSM_API.Interaction.Update("MainLoop");
Join the conversation! Your thoughts help the community grow.