From 98b8d3cebb09adb8f4f52c2f344570c1f3dd6f9a Mon Sep 17 00:00:00 2001 From: ProgramSnail Date: Mon, 29 Mar 2021 23:43:14 +0300 Subject: [PATCH] Added Event Center --- src/game/game_events.cpp | 5 ++ src/game/game_events.hpp | 108 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 113 insertions(+) diff --git a/src/game/game_events.cpp b/src/game/game_events.cpp index e69de29..40c681a 100644 --- a/src/game/game_events.cpp +++ b/src/game/game_events.cpp @@ -0,0 +1,5 @@ +#include "game_events.hpp" + +namespace events { + +} \ No newline at end of file diff --git a/src/game/game_events.hpp b/src/game/game_events.hpp index e69de29..94f8c59 100644 --- a/src/game/game_events.hpp +++ b/src/game/game_events.hpp @@ -0,0 +1,108 @@ +#include +#include +#include +#include + +#pragma once + +namespace events { + class EventId { + private: + std::string name = ""; + + int nameHash = std::hash{}(""); + + public: + EventId() = default; + + EventId(std::string name) : name(name) { + nameHash = std::hash{}(name); + } + + bool operator==(const EventId& eId) const { + return nameHash == eId.nameHash && name == eId.name; + } + + bool operator!=(const EventId& eId) const { + return !operator==(eId); + } + }; + + class EventData { // may be changed + private: + using T = int; + + std::map data; + + public: + EventData() {} + + void setField(const std::string& key, const T& value) { + data[key] = value; + } + + const T& getField(const std::string& key) { + return data[key]; + } + }; + + class Event { + private: + EventId id; + + EventData data; + + public: + Event(const EventId& id, const EventData& data) : + id(id), data(data) {} + + bool isId(const EventId& eId) const { + return id == eId; + } + + EventData& getData() { + return data; + } + + const EventData& getData() const { + return data; + } + }; + + class EventHandler { + private: + std::function handler; + + EventId eventId; + public: + EventHandler(std::function handler, + const EventId& eventId) : handler(handler), eventId(eventId) {} + + bool handleEvent(const Event& event) { + if (event.isId(eventId)) { + handler(event.getData()); + return true; + } + return false; + } + }; + + class EventCenter { + private: + std::set handlers; + public: + void addEventHandler(const EventHandler& handler) { + handlers.insert(handler); + } + + void removeEventHandler(const EventHandler& handler) { + handlers.erase(handler); + } + + void invokeEvent(const Event& event) { + for (auto handler : handlers) { + handler.handleEvent(event); + } + } + }; +} \ No newline at end of file