StateMachine.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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-17
  7. *
  8. * */
  9. #include "StateMachine.hpp"
  10. #include <utility>
  11. ls_std::StateMachine::StateMachine(std::string _name) :
  12. Class("StateMachine"),
  13. name(std::move(_name))
  14. {}
  15. bool ls_std::StateMachine::addState(const std::shared_ptr<State>& _state) {
  16. bool condition = !this->_hasState(_state->getId());
  17. if(condition) {
  18. this->states.insert({_state->getId(), _state});
  19. condition = this->_hasState(_state->getId());
  20. }
  21. return condition;
  22. }
  23. std::shared_ptr<ls_std::State> ls_std::StateMachine::getCurrentState() {
  24. return this->currentState;
  25. }
  26. std::vector<ls_std::StateId> ls_std::StateMachine::getMemory() {
  27. return this->memory;
  28. }
  29. std::string ls_std::StateMachine::getName() {
  30. return this->name;
  31. }
  32. std::unordered_map<ls_std::StateId, std::shared_ptr<ls_std::State>> ls_std::StateMachine::getStates()
  33. {
  34. return this->states;
  35. }
  36. bool ls_std::StateMachine::hasState(const StateId &_id)
  37. {
  38. return this->_hasState(_id);
  39. }
  40. bool ls_std::StateMachine::proceed() {
  41. std::vector<ls_std::StateId> nextValidStates = this->_getNextValidStates();
  42. bool condition = nextValidStates.size() == 1;
  43. if(condition) {
  44. this->currentState = this->states[nextValidStates.at(0)];
  45. this->_remember(nextValidStates.at(0));
  46. }
  47. return condition;
  48. }
  49. void ls_std::StateMachine::setName(std::string _name)
  50. {
  51. this->name = std::move(_name);
  52. }
  53. bool ls_std::StateMachine::setStartState(const ls_std::StateId&_id) {
  54. bool exists = this->_hasState(_id);
  55. if(exists) {
  56. this->currentState = this->states[_id];
  57. this->_remember(_id);
  58. }
  59. return exists;
  60. }
  61. std::vector<ls_std::StateId> ls_std::StateMachine::_getNextValidStates() {
  62. std::vector<ls_std::StateId> validStates {};
  63. for(const auto& state : this->currentState->getConnectedStates()) {
  64. if(state.second->isPassable()) {
  65. validStates.push_back(state.second->getStateId());
  66. }
  67. }
  68. return validStates;
  69. }
  70. void ls_std::StateMachine::_remember(const ls_std::StateId &_id) {
  71. this->memory.push_back(_id);
  72. }
  73. bool ls_std::StateMachine::_hasState(const ls_std::StateId &_id) {
  74. return this->states.find(_id) != this->states.end();
  75. }