StateMachine.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Author: Patrick-Christopher Mattulat
  3. * Company: Lynar Studios
  4. * E-Mail: webmaster@lynarstudios.com
  5. * Created: 2020-09-05
  6. * Changed: 2020-09-10
  7. *
  8. * */
  9. #include "StateMachine.hpp"
  10. ls_std::StateMachine::StateMachine(std::string _name) :
  11. Class("StateMachine"),
  12. name(std::move(_name))
  13. {}
  14. bool ls_std::StateMachine::addState(const std::shared_ptr<State>& _state) {
  15. bool condition = !this->_stateExists(_state->getId());
  16. if(condition) {
  17. this->states.insert({_state->getId(), _state});
  18. condition = this->_stateExists(_state->getId());
  19. }
  20. return condition;
  21. }
  22. std::shared_ptr<ls_std::State> ls_std::StateMachine::getCurrentState() {
  23. return this->currentState;
  24. }
  25. std::string ls_std::StateMachine::getName() {
  26. return this->name;
  27. }
  28. bool ls_std::StateMachine::proceed() {
  29. std::vector<ls_std::StateId> nextValidStates = this->_getNextValidStates();
  30. bool condition = nextValidStates.size() == 1;
  31. if(condition) {
  32. this->currentState = this->states[nextValidStates.at(0)];
  33. }
  34. return condition;
  35. }
  36. bool ls_std::StateMachine::setStartState(const ls_std::StateId&_id) {
  37. bool exists = this->_stateExists(_id);
  38. if(exists) {
  39. this->currentState = this->states[_id];
  40. }
  41. return exists;
  42. }
  43. std::vector<ls_std::StateId> ls_std::StateMachine::_getNextValidStates() {
  44. std::vector<ls_std::StateId> validStates {};
  45. for(const auto& state : this->currentState->getConnectedStates()) {
  46. if(state.second->isPassable()) {
  47. validStates.push_back(state.second->getStateId());
  48. }
  49. }
  50. return validStates;
  51. }
  52. bool ls_std::StateMachine::_stateExists(const ls_std::StateId &_id) {
  53. return this->states.find(_id) != this->states.end();
  54. }