Quote:
Originally Posted by nisim777
Then if they say 'jump head' it does the same thing, with the appropriate description. I'm on my way to grasping it and then I run into the need for conditionals. If they examine the head, then jump on the head, and then examine it again, the last examine statement for that head needs to be different, like 'the head is crushed.'
|
As DaWei says, you'd encapsulate the conditionals in the object itself. For example:
class Room(object):
def __init__(self, description):
self.description = description
self.exits = {}
self.items = []
def find_item(self, name):
for item in self.items:
if item.name == name:
return item
class Player(object):
def examine(self, noun):
self.action("examine", noun)
def jump(self, noun):
self.action("jump", noun);
def action(self, verb, noun)
item = self.room.find_item(noun)
method = "on_" + verb
if item is None:
print "I don't see that anywhere."
elif method not in dir(item):
print "You can't %0 on that!" % verb
else:
getattr(item, method)()
class Head(object):
def __init__(self):
self.name = "head"
self.state = "intact"
def on_examine(self):
if self.state == "intact":
print "An intact head."
elif self.state == "crushed":
print "A horribly crushed head."
def on_jump(self):
print "You jump on the head"
self.state = "crushed"
The above code is complex, but shouldn't contain too many strange features. The only bits you might not have run across are "dir" and "getattr".
dir gets you the names of all the attributes of an object (methods, variables, etc.), whilst
getattr gets a named attribute from an object. So
getattr(item, "on_jump") is the same as
item.onjump.
Sorry to keep throwing code at you! If you need any explanations, I'll be happy to expand on anything that's difficult to understand.