onilink_

State Machine

Mar 17th, 2015
375
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.17 KB | None | 0 0
  1. #ifndef TERRA_FSM_HEADER
  2. #define TERRA_FSM_HEADER
  3.  
  4. #include <vector>
  5.  
  6. namespace terra
  7. {
  8.  
  9. template<class T>
  10. class FiniteStateMachine
  11. {
  12. public:
  13.     virtual ~FiniteStateMachine() {}
  14.    
  15.     virtual void reset(const T & player) {}
  16.     virtual void create(T & player) {}
  17.     virtual void beginStep(T & player, float dt) {}
  18.     virtual void step(T & player, float dt) {}
  19.     virtual void endStep(T & player, float dt) {}
  20.     virtual void draw(const T & player, float dx, float dy) const {}
  21. };
  22.  
  23. template<class T>
  24. class FiniteStateMachineUser
  25. {
  26.     FiniteStateMachine<T> * m_currentState;
  27.     std::vector<FiniteStateMachine<T>*> m_states;
  28.     int m_currentStateInd;
  29.    
  30. public:
  31.     FiniteStateMachineUser(): m_currentState(nullptr), m_currentStateInd(-1) {}
  32.     virtual ~FiniteStateMachineUser()
  33.     {
  34.         for(auto * state : m_states)
  35.             delete state;
  36.     }
  37.    
  38.     void setState(int state, T & player)
  39.     {
  40.         m_currentState = m_states[state];
  41.         m_currentStateInd = state;
  42.         if(m_currentState)
  43.         {
  44.             m_currentState->reset(player);
  45.             m_currentState->create(player);
  46.         }
  47.     }
  48.    
  49.     int getStateIndex() const
  50.     {
  51.         return m_currentStateInd;
  52.     }
  53.    
  54.     void beginState(T & player, float dt)
  55.     {
  56.         if(m_currentState)
  57.         {
  58.             m_currentState->beginStep(player, dt);
  59.         }
  60.     }
  61.    
  62.     void updateState(T & player, float dt)
  63.     {
  64.         if(m_currentState)
  65.         {
  66.             m_currentState->step(player, dt);
  67.         }
  68.     }
  69.    
  70.     void endState(T & player, float dt)
  71.     {
  72.         if(m_currentState)
  73.         {
  74.             m_currentState->endStep(player, dt);
  75.         }
  76.     }
  77.    
  78.     void drawState(const T & player, float dx, float dy) const
  79.     {
  80.         if(m_currentState)
  81.         {
  82.             m_currentState->draw(player, dx, dy);
  83.         }
  84.     }
  85.    
  86.     template<class U, class... Args>
  87.     void createState(int ind, Args&&...args)
  88.     {
  89.         if(ind >= m_states.size())
  90.         {
  91.             m_states.resize(ind + 1, nullptr);
  92.         }
  93.         m_states[ind] = new U(std::forward<Args>(args)...);
  94.     }
  95. };
  96.  
  97. }
  98.  
  99. #endif
Advertisement
Add Comment
Please, Sign In to add comment