View Single Post
Old Sep 25th, 2005, 1:56 PM   #5
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
If you're interested, here's a small piece of sample code for part of an adventure game. If you run this code you'll be given a prompt. "inventory" shows your inventory, "look hat/stick" looks at the specific items, and "quit" quits the program. More items and verbs can easily be added.

If you want me to, I'll give you a step-by-step run down of what it all means.

class Item:
   def __init__(self, name, description):
      self.name = name
      self.description = description

inventory = [ 
      Item("hat", "A battered green hat"),
      Item("stick", "A sturdy walking stick")
]

def a_an(word):
   if word[0] in "aeiou":
      return "an " + word
   else:
      return "a " + word

def view_inventory():
   for item in inventory:
      print a_an(item.name)

def look_at_item(name):
   matching_items = [item for item in inventory if item.name == name]
   first_item = matching_items[0]
   print first_item.description

verbs = {
   'inventory' : view_inventory,
   'look' : look_at_item
}

input = ""
while True:
   input = raw_input("> ")

   if input == "quit":
      break

   words = input.split()
   first_word = words[0]
   other_words = words[1:]

   try:
      verbs[first_word](*other_words)
   except TypeError:
      print "I don't know what you mean."
   except KeyError:
      print "I don't know what you mean."
Arevos is offline   Reply With Quote