Skip to content

Commit

Permalink
Add message bus
Browse files Browse the repository at this point in the history
  • Loading branch information
vesper-arch committed Aug 11, 2024
1 parent 7931350 commit 56da2e8
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions message_bus_tools.py
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)

0 comments on commit 56da2e8

Please sign in to comment.