AlexSmithCore

StateMachine

Jan 25th, 2022 (edited)
653
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  // Example How To Add State Transition:
  2. // Here we can use the FactoryMethod to setup all transitions
  3. // 1. Creating some context class with a bunch of data:
  4. IdleContext idleContext = new IdleContext();
  5. // 2. Creating state instance and adding context to ctr parameters
  6. WanderBrainState wanderBrainState = new WanderBrainState(idleContext, _movable);
  7. // 3. Creating new instance of state transition
  8. StateTransition idleToWand = new StateTransition(idleBrainState, wanderBrainState,
  9.     ()=> idleContext.IsWander);
  10. // 4. And then we need to put this parameters to ctr of state machine
  11. // That's all.
  12.  
  13. namespace States
  14. {
  15.     public class StateMachine
  16.     {
  17.         public StateMachine(IState baseState, params StateTransition[] transitions)
  18.         {
  19.             SetState(baseState);
  20.            
  21.             _transitions = transitions;
  22.         }
  23.  
  24.         private IState _currentState;
  25.         private readonly StateTransition[] _transitions;
  26.  
  27.         private void SetState(IState state)
  28.         {
  29.             _currentState?.Exit();  
  30.             _currentState = state;
  31.             _currentState.Enter();
  32.         }
  33.  
  34.         public void Process()
  35.         {
  36.             foreach (var transition in _transitions)
  37.             {
  38.                 if (transition.TryTransit(out IState state))
  39.                 {
  40.                     if(!transition.IsCompareToFromState(_currentState)) continue;
  41.                    
  42.                     SetState(state);
  43.                     break;
  44.                 }
  45.             }
  46.            
  47.             _currentState.Process();
  48.         }
  49.     }
  50. }
RAW Paste Data Copied