Created
October 8, 2013 05:42
-
-
Save damianesteban/6879993 to your computer and use it in GitHub Desktop.
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
# 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