StateMachine.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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-11
  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::vector<ls_std::StateId> ls_std::StateMachine::getMemory() {
  26. return this->memory;
  27. }
  28. std::string ls_std::StateMachine::getName() {
  29. return this->name;
  30. }
  31. bool ls_std::StateMachine::proceed() {
  32. std::vector<ls_std::StateId> nextValidStates = this->_getNextValidStates();
  33. bool condition = nextValidStates.size() == 1;
  34. if(condition) {
  35. this->currentState = this->states[nextValidStates.at(0)];
  36. this->_remember(nextValidStates.at(0));
  37. }
  38. return condition;
  39. }
  40. bool ls_std::StateMachine::setStartState(const ls_std::StateId&_id) {
  41. bool exists = this->_stateExists(_id);
  42. if(exists) {
  43. this->currentState = this->states[_id];
  44. this->_remember(_id);
  45. }
  46. return exists;
  47. }
  48. std::vector<ls_std::StateId> ls_std::StateMachine::_getNextValidStates() {
  49. std::vector<ls_std::StateId> validStates {};
  50. for(const auto& state : this->currentState->getConnectedStates()) {
  51. if(state.second->isPassable()) {
  52. validStates.push_back(state.second->getStateId());
  53. }
  54. }
  55. return validStates;
  56. }
  57. void ls_std::StateMachine::_remember(const ls_std::StateId &_id) {
  58. this->memory.push_back(_id);
  59. }
  60. bool ls_std::StateMachine::_stateExists(const ls_std::StateId &_id) {
  61. return this->states.find(_id) != this->states.end();
  62. }