-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
vesper-arch
committed
Aug 11, 2024
1 parent
7931350
commit 56da2e8
Showing
1 changed file
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
from ansi_tags import ansiprint | ||
from enum import StrEnum | ||
from uuid import UUID, uuid4 | ||
|
||
class Event(StrEnum): | ||
START_OF_TURN = "start_of_turn" | ||
END_OF_TURN = "end_of_turn" | ||
START_OF_COMBAT = "start_of_combat" | ||
END_OF_COMBAT = "end_of_combat" | ||
|
||
class MessageBus(): | ||
def __init__(self, debug=True) -> None: | ||
self.subscribers = dict(dict()) | ||
self.debug = debug | ||
|
||
def subscribe(self, event: Event, uid: UUID, callbk_func): | ||
if event not in self.subscribers: | ||
self.subscribers[event] = dict() | ||
self.subscribers[event][uid] = callbk_func | ||
if self.debug is True: | ||
ansiprint(f"<basic>MESSAGEBUS</basic>: <blue>{event}</blue> | Subscribed <bold>{callbk_func.__qualname__}</bold>") | ||
|
||
def unsubscribe(self, event: Event, uid: UUID): | ||
if self.debug is True: | ||
ansiprint(f"<basic>MESSAGEBUS</basic>: <blue>{event}</blue> | Unsubscribed <bold>{self.subscribers[event][uid].__qualname__}</bold>") | ||
del self.subscribers[event][uid] | ||
|
||
def event_call(self, event, data): | ||
if event in self.subscribers: | ||
for _uid, callback in self.subscribers[event].items(): | ||
if self.debug: | ||
ansiprint(f"<basic>MESSAGEBUS</basic>: <blue>{event}</blue> | Calling <bold>{callback.__qualname__}</bold>") | ||
callback(event, data) | ||
return data | ||
|
||
class Registerable(): | ||
events = [] | ||
def register(self, bus): | ||
for event in self.events: | ||
bus.subscribe(event, self.uid, self.callback) | ||
|
||
def unregister(self, bus, event=None): | ||
if event: | ||
bus.unsubscribe(event, self.uid) | ||
else: | ||
for event in self.events: | ||
bus.unsubscribe(event, self.uid) | ||
|