from pygame.event import get, pump, Event, post from pygame.locals import * from GameChild import GameChild from Input import Input class Delegate(GameChild): def __init__(self, game): GameChild.__init__(self, game) self.subscribers = dict() self.load_configuration() self.disable() def load_configuration(self): config = self.get_configuration("event") self.cancel_flag_key = config["cancel-flag-key"] self.command_key = config["command-key"] self.command_event_id = config["command-id-offset"] + \ globals()[config["user-event-id"]] def disable(self): self.enabled = False def enable(self): self.enabled = True self.interpolator = self.get_game().interpolator def dispatch(self): if self.enabled: subscribers = self.subscribers for evt in get(): kind = evt.type if kind in subscribers: for subscriber in subscribers[kind]: if not self.interpolator.is_gui_active() or \ hasattr(subscriber, "im_class") and \ (subscriber.im_class == Input or \ subscriber.im_class == \ self.interpolator.gui.__class__): self.print_debug("Passing %s to %s" % (evt, subscriber)) subscriber(evt) else: pump() def add_subscriber(self, callback, kind=None): self.print_debug("Subscribing %s to %s" % (callback, kind)) if kind is None: kind = self.command_event_id subscribers = self.subscribers if kind not in subscribers: subscribers[kind] = list() subscribers[kind].append(callback) def is_command(self, event): return event.type == self.command_event_id def remove_subscriber(self, callback, kind=None): if kind is None: kind = self.command_event_id self.subscribers[kind].remove(callback) def compare(self, evt, commands=None, cancel=False, **attributes): if evt.type == self.command_event_id: self.add_cancel_flag_to_attributes(attributes, cancel) if commands is not None and not isinstance(commands, list): commands = [commands] if commands is not None: if not self.command_in_list(evt, commands): return False return all(key in evt.dict and evt.dict[key] == value for \ key, value in attributes.iteritems()) def add_cancel_flag_to_attributes(self, attributes, cancel): attributes[self.cancel_flag_key] = cancel def command_in_list(self, evt, commands): return self.get_command_attribute(evt) in commands def get_command_attribute(self, evt): return evt.dict[self.command_key] def post(self, command=None, cancel=False, **attributes): attributes[self.command_key] = command self.add_cancel_flag_to_attributes(attributes, cancel) post(Event(self.command_event_id, attributes))