GameStateManager.cxx 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include "GameStateManager.hxx"
  2. GameStateManager::GameStateManager()
  3. :states_{{GameStates::Loading}}
  4. {
  5. loading_.on_enter(*this);
  6. }
  7. GameStateManager::~GameStateManager()
  8. {
  9. while (!states_.empty()) {
  10. pop_state();
  11. }
  12. }
  13. GameState* GameStateManager::enum_to_state(GameStates const state)
  14. {
  15. switch (state) {
  16. default:
  17. return &dummy_; // TODO: handle all game states
  18. case GameStates::Loading:
  19. return &loading_;
  20. case GameStates::Splash:
  21. return &splash_;
  22. case GameStates::MainMenu:
  23. return &menu_;
  24. }
  25. }
  26. GameState* GameStateManager::current()
  27. {
  28. if (states_.empty())
  29. return nullptr;
  30. return enum_to_state(states_.top());
  31. }
  32. GameState* GameStateManager::parent()
  33. {
  34. if (states_.size()<2)
  35. return nullptr;
  36. auto const current = states_.top();
  37. states_.pop();
  38. auto const parent = states_.top();
  39. states_.push(current);
  40. return enum_to_state(parent);
  41. }
  42. void GameStateManager::push_state(GameStates const new_state)
  43. {
  44. states_.push(new_state);
  45. current()->on_enter(*this);
  46. }
  47. void GameStateManager::pop_state()
  48. {
  49. auto const state = current();
  50. if (state!=nullptr) {
  51. state->on_leave();
  52. states_.pop();
  53. }
  54. }
  55. void GameStateManager::replace_state(GameStates const new_state)
  56. {
  57. pop_state();
  58. push_state(new_state);
  59. }