Created
December 8, 2015 23:44
-
-
Save bedekelly/24673c99d123539c91f0 to your computer and use it in GitHub Desktop.
Object-Oriented Events for Interactive Fiction
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
""" | |
A short example of my proposed object-oriented event framework for IF games. | |
Every event should implement a go() method, which calls super().go() before doing | |
anything else. After that, it should check whether its own go() method is | |
applicable by making a call to self.should_fire(<EventType>). | |
""" | |
class Event: | |
"""Generic Event type.""" | |
def __init__(self, obj): | |
self.obj = obj # Event is applied to this object. | |
self._interrupt_after = set() # Set of things to interrupt for. | |
self._should_continue = True # Has our event (not) been interrupted? | |
def should_fire(self, current_type): | |
"""Determine whether we should apply current_type's handler.""" | |
if not self._should_continue: | |
# We've already interrupted; don't handle the event. | |
return False | |
elif current_type in self._interrupt_after: | |
# We need to interrupt now; handle it with this type. | |
self._should_continue = False | |
return True # Handle the event with this type. | |
def go(self): | |
"""Override this method if you want your event to do something.""" | |
def interrupt_after(self, *args): | |
"""Add an arbitrary list of event types at which we interrupt.""" | |
for a in args: | |
self._interrupt_after.add(a) | |
class Touch(Event): | |
"""Sent when an object is touched.""" | |
def go(self): | |
super().go() | |
if self.should_fire(Touch): | |
print(self.obj, "was touched!") | |
class Pull(Touch): | |
"""Sent when an object is pulled.""" | |
def go(self): | |
super().go() | |
if self.should_fire(Pull): | |
print(self.obj, "was pulled!") | |
class LeverPull(Pull): | |
"""Sent when a lever is pulled.""" | |
def go(self): | |
super().go() | |
if self.should_fire(LeverPull): | |
print(self.obj, "was lever-pulled!") | |
class ElectrifiedLeverPull(LeverPull): | |
"""Sent when an electrified lever is pulled.""" | |
def go(self): | |
self.interrupt_after(Touch) | |
super().go() | |
if self.should_fire(ElectrifiedLeverPull): | |
print(self.obj, "was electric-lever-pulled!") | |
print("ZAP!") | |
class WorkingLever: | |
def __str__(self): | |
return "Working Lever" | |
class ElectrifiedLever: | |
def __str__(self): | |
return "Electrified Lever" | |
LeverPull(WorkingLever()).go() | |
print() | |
ElectrifiedLeverPull(ElectrifiedLever()).go() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment