ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Advanced State Machine Transitions with Guard Conditions

C# (Unity)

Goal -- WPM

Ready
Exercise Algorithm Area
1using System;
2
3public class AdvancedStateMachine
4{
5public enum State
6{
7Idle, Running, Paused, Stopped
8}
9
10private State currentState;
11private Action<State> onStateChanged;
12
13public AdvancedStateMachine(State initialState, Action<State> stateChangedCallback = null)
14{
15currentState = initialState;
16onStateChanged = stateChangedCallback;
17Console.WriteLine($"Initial state: {currentState}");
18}
19
20public bool CanTransition(State nextState)
21{
22// Guard conditions for transitions
23if (currentState == nextState) return false;
24
25switch (currentState)
26{
27case State.Idle:
28return nextState == State.Running;
29case State.Running:
30return nextState == State.Paused || nextState == State.Stopped;
31case State.Paused:
32return nextState == State.Running || nextState == State.Stopped;
33case State.Stopped:
34return false; // Cannot transition from stopped state
35default:
36return false;
37}
38}
39
40public bool TransitionTo(State nextState)
41{
42if (!CanTransition(nextState))
43{
44Console.WriteLine($"Cannot transition from {currentState} to {nextState}.");
45return false;
46}
47
48Console.WriteLine($"Transitioning from {currentState} to {nextState}.");
49currentState = nextState;
50
51onStateChanged?.Invoke(currentState);
52return true;
53}
54
55public State GetCurrentState()
56{
57return currentState;
58}
59
60public static void Main(string[] args)
61{
62var machine = new AdvancedStateMachine(State.Idle, (state) => Console.WriteLine($"State changed to: {state}"));
63
64// Test valid transitions
65machine.TransitionTo(State.Running);
66machine.TransitionTo(State.Paused);
67machine.TransitionTo(State.Running);
68machine.TransitionTo(State.Stopped);
69
70// Test invalid transitions
71machine.TransitionTo(State.Running); // Should fail
72machine.TransitionTo(State.Idle); // Should fail
73
74// Test transition from a state that cannot transition
75var stoppedMachine = new AdvancedStateMachine(State.Stopped);
76stoppedMachine.TransitionTo(State.Running); // Should fail
77}
78}
Algorithm description viewbox

Advanced State Machine Transitions with Guard Conditions

Algorithm description:

This C# code implements an advanced state machine with explicit guard conditions for transitions. It allows for controlled movement between defined states, ensuring that transitions only occur when specific criteria are met. This pattern is crucial in game development for managing player actions, AI behaviors, and UI states.

Algorithm explanation:

The `AdvancedStateMachine` class manages a finite set of states and defines valid transitions between them using guard conditions. The `CanTransition` method acts as the gatekeeper, evaluating the current state and the desired next state against predefined rules. If `CanTransition` returns true, the `TransitionTo` method updates the `currentState` and optionally invokes a callback. The complexity of `CanTransition` is O(N) where N is the number of states, as it might involve a switch statement. However, in practice, with a fixed number of states, it's effectively O(1). The space complexity is O(1) as it only stores the current state and a callback. Edge cases include attempting to transition to the same state, transitioning from a terminal state (like 'Stopped'), or attempting an undefined transition, all of which are handled by `CanTransition` returning false.

Pseudocode:

Class AdvancedStateMachine:
  Enum State { Idle, Running, Paused, Stopped }
  CurrentState
  OnStateChangedCallback

  Constructor(initialState, callback):
    Set CurrentState to initialState
    Set OnStateChangedCallback to callback

  Method CanTransition(nextState):
    If CurrentState is same as nextState, return false
    Switch on CurrentState:
      Case Idle: return nextState is Running
      Case Running: return nextState is Paused or Stopped
      Case Paused: return nextState is Running or Stopped
      Case Stopped: return false
    Default: return false

  Method TransitionTo(nextState):
    If CanTransition(nextState) is false:
      Print error message
      Return false
    Print transition message
    Set CurrentState to nextState
    Invoke OnStateChangedCallback with CurrentState
    Return true

  Method GetCurrentState():
    Return CurrentState