Simple C++ Game
StateMachine.hpp
1 #pragma once
2 
3 #include <Dispatcher.hpp>
4 #include <Event.hpp>
5 
6 #include <SFML/System.hpp>
7 
8 #include <map>
9 #include <functional>
10 #include <memory>
11 
13 {
14 public:
15  class State;
16  class StateTransition;
17 
18  class State
19  {
20  public:
21  State(StateMachine &owner);
22  virtual ~State() = default;
23 
24  virtual void entry();
25  virtual void exit();
26  virtual void update(const sf::Time deltaT);
27 
28  void handleEvent(const Event &event);
29 
30  void registerEventResponse(const std::string eventId, const std::function<void(const Event &)> response);
31  void registerTransition(const std::string eventId, const StateTransition &transition);
32  void registerTransition(const std::string eventId, std::shared_ptr<State> &target);
33 
34  private:
35  StateMachine &_owner;
36  Dispatcher _eventResponse;
37  };
38 
40  {
41  public:
42  StateTransition(std::shared_ptr<State> &target);
43  virtual ~StateTransition() = default;
44 
45  std::shared_ptr<State> &getTargetState() const;
46  virtual bool guard(const Event &trigger) const;
47  virtual void effect() const;
48 
49  private:
50  std::shared_ptr<State> &_target;
51  };
52 
53  StateMachine(Dispatcher &dispatcher);
54 
55  void start(std::shared_ptr<State> &initialState);
56  bool isStarted() const;
57  void update(const sf::Time deltaT);
58  void executeTransition(const StateTransition &transition);
59  Dispatcher &getDispatcher() const;
60  State &getState() const;
61 
62 private:
63  Dispatcher &_dispatcher;
64  std::shared_ptr<State> _currentState;
65 
66  void setState(std::shared_ptr<State> &state);
67  void passEventToCurrentState(const Event &event);
68 };
A class for managing events.
Definition: Dispatcher.hpp:18
A class representing an event that has occurred.
Definition: Event.hpp:10
Definition: StateMachine.hpp:40
Definition: StateMachine.hpp:19
Definition: StateMachine.hpp:13