using System; using System.Collections.Generic; namespace RebootKit.Engine.Foundation { public interface IState { void Enter(); void Exit(); } public class StateMachine where TState : class, IState { readonly Dictionary m_States; IState m_ActiveState; public StateMachine() { m_States = new Dictionary(); m_ActiveState = null; } public StateMachine(IEnumerable states) { foreach (TState state in states) { AddState(state); } } public void AddState(TState state) { Type type = state.GetType(); if (!m_States.TryAdd(type, state)) { throw new Exception($"State {type} already exists in the state machine."); } } public void TransitionTo() where TStateType : class, TState { Type type = typeof(TStateType); if (!m_States.TryGetValue(type, out TState newState)) { throw new Exception($"State {type} not found in the state machine."); } m_ActiveState?.Exit(); m_ActiveState = newState; m_ActiveState.Enter(); } public bool IsStateActive() where TStateType : class, TState => m_ActiveState != null && m_ActiveState.GetType() == typeof(TStateType); } }