Thread: Why OOP?
View Single Post
Old Oct 11th, 2007, 7:07 AM   #33
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
Quote:
Originally Posted by nisim777 View Post
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:

python Syntax (Toggle Plain Text)
  1. class Room(object):
  2. def __init__(self, description):
  3. self.description = description
  4. self.exits = {}
  5. self.items = []
  6.  
  7. def find_item(self, name):
  8. for item in self.items:
  9. if item.name == name:
  10. return item
  11.  
  12. class Player(object):
  13. def examine(self, noun):
  14. self.action("examine", noun)
  15.  
  16. def jump(self, noun):
  17. self.action("jump", noun);
  18.  
  19. def action(self, verb, noun)
  20. item = self.room.find_item(noun)
  21. method = "on_" + verb
  22.  
  23. if item is None:
  24. print "I don't see that anywhere."
  25. elif method not in dir(item):
  26. print "You can't %0 on that!" % verb
  27. else:
  28. getattr(item, method)()
  29.  
  30. class Head(object):
  31. def __init__(self):
  32. self.name = "head"
  33. self.state = "intact"
  34.  
  35. def on_examine(self):
  36. if self.state == "intact":
  37. print "An intact head."
  38. elif self.state == "crushed":
  39. print "A horribly crushed head."
  40.  
  41. def on_jump(self):
  42. print "You jump on the head"
  43. 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.
Arevos is offline   Reply With Quote