Advertisement
Zenn_

Statemachine.cpp

Jul 17th, 2018
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.87 KB | None | 0 0
  1. #include "StateMachine.h"
  2.  
  3. namespace station {
  4.     void StateMachine::AddState(StateReference newState, bool isReplacing) {
  5.         /*since we are adding a State to the Stack, lets
  6.         set _isAdding to true*/
  7.         this->_isAdding = true;
  8.         /*we established whether we're replacing the top level active State
  9.         or not in the method parameters already*/
  10.         this->_isReplacing = isReplacing;
  11.  
  12.         /*set given newState StateReference as _newState in the Statemachine*/
  13.         this->_newState = std::move(newState);
  14.     }
  15.     void StateMachine::RemoveState() {
  16.         /*sets _isRemoving to true, so when we call ProcessStateChanges, it will
  17.         pop the top level active State */
  18.         this->_isRemoving = true;
  19.     }
  20.     void StateMachine::ProcessStateChanges() {
  21.         if (!this->_states.empty() && this->_isRemoving) {
  22.             /*If the stack is not empty and we want to pop the top level active State,
  23.             do just that*/
  24.             this->_states.pop();
  25.             if (!this->_states.empty()) {
  26.                 /*If the stack isnt empty now, the new top level State is not the active
  27.                 State and needs to be resumed*/
  28.                 this->_states.top()->resume();
  29.             }
  30.             /*done removing state*/
  31.             this->_isRemoving = false;
  32.         }
  33.         if (this->_isAdding) {
  34.             /*if we want to add a state...*/
  35.             if (this->_isReplacing) {
  36.                 /*check if we want to replace the top level State,
  37.                 in which case we need to pop it first.*/
  38.                 this->_states.pop();
  39.             }
  40.             else {
  41.                 /*if we dont replace the top level active State, we will need to pause it
  42.                 since it wont be active anymore when we push the new State to the Stack*/
  43.                 this->_states.top()->pause();
  44.             }
  45.             /*push the new State to the stack and call its initialize function*/
  46.             this->_states.push(std::move(this->_newState));
  47.             this->_states.top()->initialize();
  48.             /*done adding state*/
  49.             this->_isAdding = false;
  50.         }
  51.     }
  52.     StateReference &StateMachine::GetActiveState() {
  53.         return this->_states.top();
  54.     };
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement