Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef TERRA_FSM_HEADER
- #define TERRA_FSM_HEADER
- #include <vector>
- namespace terra
- {
- template<class T>
- class FiniteStateMachine
- {
- public:
- virtual ~FiniteStateMachine() {}
- virtual void reset(const T & player) {}
- virtual void create(T & player) {}
- virtual void beginStep(T & player, float dt) {}
- virtual void step(T & player, float dt) {}
- virtual void endStep(T & player, float dt) {}
- virtual void draw(const T & player, float dx, float dy) const {}
- };
- template<class T>
- class FiniteStateMachineUser
- {
- FiniteStateMachine<T> * m_currentState;
- std::vector<FiniteStateMachine<T>*> m_states;
- int m_currentStateInd;
- public:
- FiniteStateMachineUser(): m_currentState(nullptr), m_currentStateInd(-1) {}
- virtual ~FiniteStateMachineUser()
- {
- for(auto * state : m_states)
- delete state;
- }
- void setState(int state, T & player)
- {
- m_currentState = m_states[state];
- m_currentStateInd = state;
- if(m_currentState)
- {
- m_currentState->reset(player);
- m_currentState->create(player);
- }
- }
- int getStateIndex() const
- {
- return m_currentStateInd;
- }
- void beginState(T & player, float dt)
- {
- if(m_currentState)
- {
- m_currentState->beginStep(player, dt);
- }
- }
- void updateState(T & player, float dt)
- {
- if(m_currentState)
- {
- m_currentState->step(player, dt);
- }
- }
- void endState(T & player, float dt)
- {
- if(m_currentState)
- {
- m_currentState->endStep(player, dt);
- }
- }
- void drawState(const T & player, float dx, float dy) const
- {
- if(m_currentState)
- {
- m_currentState->draw(player, dx, dy);
- }
- }
- template<class U, class... Args>
- void createState(int ind, Args&&...args)
- {
- if(ind >= m_states.size())
- {
- m_states.resize(ind + 1, nullptr);
- }
- m_states[ind] = new U(std::forward<Args>(args)...);
- }
- };
- }
- #endif
Advertisement
Add Comment
Please, Sign In to add comment