Skip to content

Instantly share code, notes, and snippets.

@damianesteban
Created October 8, 2013 05:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save damianesteban/6879993 to your computer and use it in GitHub Desktop.
Save damianesteban/6879993 to your computer and use it in GitHub Desktop.
# One option would be to use a signal system
# Firstly, we have a reusable class that lets you define a signal
class Signal(object):
def __init__(self):
self._handlers = []
def connect(self, handler):
self._handlers.append(handler)
def fire(self, *args):
for handler in self._handlers:
handler(*args)
# Your item class uses this signal to create a destroyed signal that other classes can listen for.
class Item(object):
def __init__(self):
self.destroyed = Signal()
def destroy(self):
self.destroyed.fire(self)
# And inventory listens to the signals from the items and updates its internal state accordingly
class Inventory(object):
def __init__(self):
self._items = []
def add(self, item):
item.destroyed.connect(self.on_destroyed)
self._items.add(item)
def on_destroyed(self, item):
self._items.remove(item)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment