StateMachine.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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-16
  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->_hasState(_state->getId());
  16. if(condition) {
  17. this->states.insert({_state->getId(), _state});
  18. condition = this->_hasState(_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. std::unordered_map<ls_std::StateId, std::shared_ptr<ls_std::State>> ls_std::StateMachine::getStates()
  32. {
  33. return this->states;
  34. }
  35. bool ls_std::StateMachine::hasState(const StateId &_id)
  36. {
  37. return this->_hasState(_id);
  38. }
  39. bool ls_std::StateMachine::proceed() {
  40. std::vector<ls_std::StateId> nextValidStates = this->_getNextValidStates();
  41. bool condition = nextValidStates.size() == 1;
  42. if(condition) {
  43. this->currentState = this->states[nextValidStates.at(0)];
  44. this->_remember(nextValidStates.at(0));
  45. }
  46. return condition;
  47. }
  48. bool ls_std::StateMachine::setStartState(const ls_std::StateId&_id) {
  49. bool exists = this->_hasState(_id);
  50. if(exists) {
  51. this->currentState = this->states[_id];
  52. this->_remember(_id);
  53. }
  54. return exists;
  55. }
  56. std::vector<ls_std::StateId> ls_std::StateMachine::_getNextValidStates() {
  57. std::vector<ls_std::StateId> validStates {};
  58. for(const auto& state : this->currentState->getConnectedStates()) {
  59. if(state.second->isPassable()) {
  60. validStates.push_back(state.second->getStateId());
  61. }
  62. }
  63. return validStates;
  64. }
  65. void ls_std::StateMachine::_remember(const ls_std::StateId &_id) {
  66. this->memory.push_back(_id);
  67. }
  68. bool ls_std::StateMachine::_hasState(const ls_std::StateId &_id) {
  69. return this->states.find(_id) != this->states.end();
  70. }