#!/usr/bin/env python
'''
'''

import sys
import os
import time
import pickle

class SavedState():
	def __init__(self):
		self.riverCrossingDirection=-1
		self.currentLocation='gianthall'	# name of room you are 'in'
		self.ogreQuelled=False			# whether the ogre is 'quelled' (i.e., you have given him the bottle of whiskey)
		self.manholeOpen=False			# whether manhole is open
		self.manholeUnlocked=False		# whether manhole is unlocked
		self.windowOpen=False
		self.lookedInCellar=False
		self.torchIsLit=False
		self.itemsCarried=0			# number of objects being carried by you (max is 5)
		self.dwarfIsDead=False			# whether the dwarf in the way is dead
		self.guardIsAdorned=False		# whether the guard is 'adorned' (i.e., you have given him the golden medal)
		self.promptEnteringRoom=False
		self.objects = {}
                self.location = {}

class GameSession():
	"top level class for the program"

	def do_cmd_go(self,noun,verb,cmdPrefix,cmdSuffix):
		if verb == "n**" or verb == "s**" or verb == "e**" or verb == "w**":
			return self.do_cmd_movement(noun, verb, cmdPrefix, cmdSuffix)
		if verb == "nor" or verb == "sou" or verb == "eas" or verb == "wes":
			return self.do_cmd_movement(noun, verb, cmdPrefix, cmdSuffix)
		if noun == "***":
			print "I need a Noun too!"
			return False
		if noun == "win":
			if (self.state.currentLocation != 'attic'
                            or not self.state.windowOpen):
				print "Not now ..."
				return False
			self.state.currentLocation='hugegarden'
			return True
		if noun == "lar":
			if self.state.currentLocation != 'kitchen':
				print "Not now ..."
				return False
			self.state.currentLocation='larder'
			return True
		if noun == "ros" or noun == "bed":
			if self.state.currentLocation != 'garden1':
				print "Not now ..."
				return False
			self.state.currentLocation='rosebed'
			return True
		if noun == "tra":
			if (self.state.currentLocation != 'bedroom'
                            and self.state.currentLocation != 'cellar'):
				print "Not now ..."
				return False
			if self.state.currentLocation == 'bedroom':
				self.state.currentLocation='cellar'
			else:
				self.state.currentLocation='bedroom'
			return True
		if noun == "lak":
			if (self.state.currentLocation != 'sublake'
                            and self.state.currentLocation != 'bysublake'):
				print "Not now ..."
				return False
			if self.state.objects['can']['location'] != 'carrying':
				print "I need a Boat."
				return False
			self.state.currentLocation='canoe'
			return True
		if noun == "man":
			if (self.state.currentLocation != 'ladder'
                            and self.state.currentLocation != 'emptyroad'):
				print "Not now ..."
				return False
			if not self.state.manholeOpen:
				print "Not now ..."
				return False
			if self.state.currentLocation == 'ladder':
				self.state.currentLocation = 'emptyroad'
				self.state.objects['man']['location']='emptyroad'
				print "OK. Below me, the ladder disappears!"
				self.state.objects['lad']['location']='rosebed'
				self.state.promptEnteringRoom=True
				return True
			print "It's a long fall ... I break my Neck!"
			print "I'm dead!"
			self.do_cmd_gameover(noun,verb,cmdPrefix,cmdSuffix)
		if noun == "sha":
			if self.state.currentLocation != 'quarry':
				print "Not now ..."
				return False
			self.state.currentLocation='shack'
			return True
		if noun == "pon":
			if self.state.currentLocation != 'pathend':
				print "Not now ..."
				return False
			newLoc = 'dampchamber'
		else:
			if noun != "poo":
				print "I can't go there."
				return False
			if self.state.currentLocation != 'courtyard':
				print "Not now ..."
				return False
			newLoc = 'pathend'
		if self.state.objects['aqu']['location'] != 'wearing':
			print "No air! ... I drown!"
			print "I'm dead!"
			self.do_cmd_gameover(noun,verb,cmdPrefix,cmdSuffix)
		self.state.currentLocation=newLoc
		print "OK."
		time.sleep(1.5)
		print "I surface."
		self.state.promptEnteringRoom=True
		return True

	def do_cmd_movement(self, noun, verb, cmdPrefix, cmdSuffix):
		if noun == "***":
			noun = verb
		if (not self.state.dwarfIsDead
                    and self.state.currentLocation == 'roadbend'
                    and (noun == "wes" or noun == "w**")):
			print "The Dwarf bars my way!"
			return False
		if (not self.state.ogreQuelled
                    and self.state.currentLocation == 'ledge'):
			print "The Ogre bars my way!"
			return False
		if (not self.state.guardIsAdorned
                    and self.state.currentLocation == 'palace'
                    and (noun == "sou" or noun == "s**")):
			print "The Guard bars my way"
			return False
		p='n'
		if noun == "sou" or noun == "s**":
			p='s'
		if noun == "e**" or noun == "eas":
			p='e'
		if noun == "w**" or noun == "wes":
			p='w'
		possibleExit=self.state.location[self.state.currentLocation]['exits'][p]
		if possibleExit:
			self.state.currentLocation=possibleExit
			return True
		if not self.state.isDark:
			print "I can't go there."
			return False
		# fall in the dark...
		print "I fall and break my   Neck!"
		self.do_cmd_gameover(noun,verb,cmdPrefix,cmdSuffix)

	def do_cmd_get(self, noun, verb, cmdPrefix, cmdSuffix):
		if noun == "***":
			print "I need a Noun too!"
			return False
		if noun == "i**" or noun == "inv":
			return self.do_cmd_inv(noun, verb, cmdPrefix, cmdSuffix)
		if noun in self.state.objects:
			obj=self.state.objects[noun]
		else:
			obj=None
		if not obj or not obj['carryable']:
			print "It's beyond my power to do that."
			return False
		if obj['location'] == 'carrying':
			print "I've already got it."
			return False
		if obj['location'] != self.state.currentLocation:
			print "I can't {0} a {1}".format(cmdPrefix,cmdSuffix)
			return False
		if self.state.itemsCarried == 5:
			print "I'm carrying too much."
			return False
		self.state.itemsCarried += 1
		obj['location'] = 'carrying'
		print "OK."
		return False;

	def do_cmd_drop(self,noun,verb,cmdPrefix,cmdSuffix):
		if noun == "***":
			print "I need a Noun too!"
			return False
		if noun in self.state.objects:
			loc = self.state.objects[noun]['location']
		else:
			loc=None
		if loc != 'carrying' and loc != 'wearing':
			print "I haven't got it."
			return False
		self.state.itemsCarried=self.state.itemsCarried-1
		if self.state.currentLocation == 'canoe':
			# in the lake, stuff disappears for good...
			print "It sinks in the Lake."
			self.state.objects[noun]['location'] = ''
			if noun != 'can':
				return False
			print"... so do I!"
			print "I'm dead!"
			self.do_cmd_gameover(noun,verb,cmdPrefix,cmdSuffix)
		if noun != 'mir':
			self.state.objects[noun]['location']=self.state.currentLocation
			print "OK."
			return False;
		# uh oh - dropped the magic mirror
		if self.state.objects['box']['location'] != self.state.currentLocation:
			print "It shatters!"
			self.do_cmd_gameover(noun,verb,cmdPrefix,cmdSuffix)
		print "It lands in its Box, lights up, and says:"
		if self.state.currentLocation != 'storeroom':
			self.state.objects['mir']['location']=self.state.currentLocation
			print "Hi there!"
			return False
		# dropped it in its box in the storeroom -- that's the ticket...
		print "*Congratulations!* You have won!"
		self.do_cmd_gameover(noun,verb,cmdPrefix,cmdSuffix)
 
	def do_cmd_inv(self,noun,verb,cmdPrefix,cmdSuffix):
		print "I am carrying:"
		found = []
		for obj in self.state.objects:
			loc = self.state.objects[obj]['location']
			if loc == 'carrying' or loc == 'wearing':
				found.append(obj)
		if len(found) == 0:
			print "Nothing at all!"
		else:
			for objName in found:
				obj = self.state.objects[objName]
				print ('  {0}{1}'.format(
                                        obj['description'],
                                        ' (worn)' if obj['location']=='wearing' else ''))
		return False

	def do_cmd_open(self,noun,verb,cmdPrefix,cmdSuffix):
		retVal = False
		if noun == "***":
			print "I need a Noun too!"
		if noun == "man":
			if self.state.currentLocation != 'ladder':
				print "Not now ..."
			elif not self.state.manholeUnlocked:
				print "It's locked."
			else:
				self.state.manholeOpen=True
				self.state.objects['man']['description']="open manhole"
				print 'OK.'
		elif noun == "win":
			if self.state.currentLocation != 'attic':
				print "Not now ..."
			else:
				self.state.objects['win']['description']="open window"
				self.state.windowOpen=True
				self.state.promptEnteringRoom=True
				retVal = True
		else:
			print "I can't {0} a {1}".format(cmdPrefix,cmdSuffix)
		return retVal

	def do_cmd_follow(self,noun,verb,cmdPrefix,cmdSuffix):
		if noun == "***":
			print "I need a Noun too!"
			return False
		if noun != "pat":
			print "I can't {0} a {1}".format(cmdPrefix,cmdSuffix)
			return False
		if self.state.currentLocation != 'garden2':
			print "Not now ..."
			return False
		self.state.currentLocation='pathend'
		return True

	def do_cmd_savegame(self,noun,verb,cmdPrefix,cmdSuffix):
                f = open('mm-game.sav', 'wb+')
                pickle.dump(self.state, f)
                f.close()
		print "OK."
		return False

	def do_cmd_readsavedgame(self,noun,verb,cmdPrefix,cmdSuffix):
                try:
                        f = open('mm-game.sav', 'rb+')
                except:
                        print 'Error reading saved game'
		        return False
                self.state = pickle.load(f)
                f.close()
		print "OK."
		return True

	def do_cmd_move(self,noun,verb,cmdPrefix,cmdSuffix):
		if noun == "***":
			print "I need a Noun too!"
			return False
		if noun == "pai" or noun == "pic":
			if self.state.currentLocation != 'bedchamber':
				print "Not now ..."
				return False
			self.state.location['bedchamber']['exits'] = (
                                { 'n': 'vault', 's': 'attic', 'e': 'kitchen', 'w': None })
			print "There's a passageway behind it!"
			self.state.promptEnteringRoom=True
			return True
		if noun == "tap":
			if self.state.currentLocation != 'vault':
				print "Not now ..."
				return False
			self.state.location['vault']['exits'] = (
                                { 'n': 'hiddenroom', 's': 'bedchamber', 'e': None, 'w': None })
			print "There's a passageway behind it!"
			self.state.promptEnteringRoom=True
			return True
		if noun == "bed":
			if self.state.currentLocation != 'bedroom':
				print "Not now ..."
				return False
			self.state.objects['tr1']['location']=self.state.currentLocation
			print "I find Something!"
			self.state.promptEnteringRoom=True
			return True
		if noun == "roc":
			if self.state.currentLocation != 'tunnel':
				print "Not now ..."
				return False
			self.state.location['tunnel']['exits'] = (
                                { 'n': 'mustycave', 's': None, 'e': None, 'w': 'ledge' })
			print "There's a passageway behind it!"
			self.state.promptEnteringRoom=True
			return True
		print "I can't {0} a {1}".format(cmdPrefix,cmdSuffix)
		return False


	def do_cmd_read(self,noun,verb,cmdPrefix,cmdSuffix):
		if noun == "***":
			print "I need a Noun too!"
		elif noun != "boo":
			print "I can't {0} a {1}".format(cmdPrefix,cmdSuffix)
		elif self.state.objects['boo']['location'] != 'carrying':
			print "I haven't got it."
		elif self.state.objects['spe']['location'] != 'wearing':
			print "The print is too small to read!"
		else:
			print "It says:\nA useful magic word is 'ZONK'."
		return False

	def do_cmd_say(self,noun,verb,cmdPrefix,cmdSuffix):
		if noun == "***":
			print "I need a Noun too!"
			return False
		print 'OK."{0}"'.format(cmdSuffix)
		if (noun != "zon"
                    or (self.state.objects['tor']['location'] != 'carrying'
                        and self.state.objects['tor']['location'] != self.state.currentLocation)):
			print "Nothing Happens."
			return False
		print "The Torch lights up!"
		self.state.objects['tor']['description']="lit TORCH"
		self.state.torchIsLit=True
		self.state.promptEnteringRoom=True
		return True

	def do_cmd_wear(self,noun,verb,cmdPrefix,cmdSuffix):
		if noun == "***":
			print "I need a Noun too!"
		if noun == "spe" or noun == "aqu":
			if self.state.objects[noun]['location'] != 'carrying':
				print "I haven't got it."
			else:
				self.state.objects[noun]['location'] = 'wearing'
				print "OK."
		else:
			print "I can't {0} a {1}".format(cmdPrefix,cmdSuffix)
		return False

	def do_cmd_climb(self,noun,verb,cmdPrefix,cmdSuffix):
		if noun == "***":
			print "I need a Noun too!"
			return False
		if noun != "lad":
			print "I can't {0} a {1}".format(cmdPrefix,cmdSuffix)
			return False
		if self.state.objects['lad']['location'] != self.state.currentLocation:
			print "It's not here!"
			return False
		if self.state.currentLocation == 'bysublake':
			self.state.currentLocation='ladder'
			self.state.promptEnteringRoom=True
			return True
		if self.state.currentLocation == 'hugegarden':
			self.state.currentLocation='attic'
			self.state.promptEnteringRoom=True
			return True
		print "Not now ..."
		return False

	def do_cmd_throw(self,noun,verb,cmdPrefix,cmdSuffix):
		if noun == "***":
			print "I need a Noun too!"
			return False
		if noun in self.state.objects:
			obj=self.state.objects[noun]
			loc = obj['location']
		else:
			obj=None
			loc=None
		if loc != 'carrying' and loc != 'wearing':
			print "I haven't got it."
			return False
		self.state.itemsCarried -= 1
		if self.state.currentLocation == 'pathend':
			print "It falls in the Pond."
			obj['location'] = 'dampchamber'
		elif self.state.currentLocation == 'canoe':
			print "It sinks in the Lake."
			obj['location'] = ''
			if noun == "can":
				print "... so do I!"
				self.do_cmd_gameover(noun,verb,cmdPrefix,cmdSuffix)
		else:
			print "OK."
			obj['location'] = self.state.currentLocation
			print "It falls at my Feet."
		return False

	def do_cmd_look(self,noun,verb,cmdPrefix,cmdSuffix):
		if noun == "***":
			return True
		if noun == "aro":
			return True
		if (noun == "tap" or noun == "pai"
                    or noun == "lar" or noun == "poo" or noun == "sha"):
			print "Something's there."
			return False
		if ((noun == "ros" or noun == "bed")
                    and self.state.objects['lad']['location'] == 'rosebed'):
			print "Something's there."
			return False
		if (noun == "pal" or noun == "gar" or noun == "win"
                    or noun == "tra" or noun == "pon"):
			print "Something's there."
			return False
		if noun == "cel":
			if self.state.currentLocation != 'cellar':
				print "It's not here!"
				return False
			if self.state.lookedInCellar:
				print "I see nothing Special."
				return False
			self.state.lookedInCellar=True
			self.state.objects['box']['location']='cellar'
			print "I find Something!"
			self.state.promptEnteringRoom=True
			return True
		if noun == "cha" or noun == "lak":
			print "It's very Deep!"
			return False
		if noun == "ogr" or noun == "gua":
			print "He wants Something!"
			return False
		if noun != "hed":
			print "I see nothing Special."
			return False
		if self.state.currentLocation != 'emptyroad':
			print "It's not here!"
			return False
		print "I find a path leading East!"
		self.state.location['emptyroad']['exits'] = (
                        { 'n': 'roadbend', 's': 'road', 'e': 'meadow', 'w': None })
		self.state.promptEnteringRoom=True
		return True

	def do_cmd_swim(self,noun,verb,cmdPrefix,cmdSuffix):
		if noun == "***":
			print "I need a Noun too!"
			return False
		if noun == "lak":
			if (self.state.currentLocation != 'sublake'
                            and self.state.currentLocation != 'canoe'
                            and self.state.currentLocation != 'bysublake'):
				print "Not now ..."
				return False
			print "It's too wide!  I've drowned!"
			print "I'm dead!"
			self.do_cmd_gameover(noun,verb,cmdPrefix,cmdSuffix)
		if noun != "str":
			print "I can't {0} a {1}".format(cmdPrefix,cmdSuffix)
			return False
		if (self.state.currentLocation != 'cavern'
                    and self.state.currentLocation != 'chasm'):
			print "Not now ..."
			return False
		if self.state.objects['aqu']['location'] != 'wearing':
			print "No air! ... I drown!"
			print "I'm dead!"
			self.do_cmd_gameover(noun,verb,cmdPrefix,cmdSuffix)
		if self.state.currentLocation == 'cavern':
			self.state.currentLocation='chasm'
                else:
		        self.state.currentLocation='cavern'
		return True

	def do_cmd_jump(self,noun,verb,cmdPrefix,cmdSuffix):
		if noun == "***":
			print "I need a Noun too!"
			return False
		if noun == "dow":
			if self.state.currentLocation != 'ladder':
				print "Not now ..."
				return False
			self.state.currentLocation='bysublake'
			return True
		if noun != "cha":
			print "I can't {0} a {1}".format(cmdPrefix,cmdSuffix)
			return False
		if (self.state.currentLocation != 'ledge'
                    and self.state.currentLocation != 'chasm'):
			print "Not now ..."
			return False
		if self.state.itemsCarried>4:
			print "I'm carrying too much!"
			print "I fall and break my Neck!"
			self.do_cmd_gameover(noun,verb,cmdPrefix,cmdSuffix)
		if self.state.currentLocation == 'ledge':
			self.state.currentLocation='chasm'
		else:
			self.state.currentLocation='ledge'
		return True
 
	def do_cmd_wait(self,noun,verb,cmdPrefix,cmdSuffix):
		print "Time passes ..."
		time.sleep(1.5)
		if self.state.currentLocation != 'canoe':
			print "Nothing Happens."
			return False
		print "The canoe reaches the Opposite Shore."
		self.state.riverCrossingDirection=-self.state.riverCrossingDirection
		if self.state.riverCrossingDirection == 1:
			self.state.currentLocation='bysublake'
		else:
			self.state.currentLocation='sublake'
		self.state.promptEnteringRoom=True
		return True
 
	def do_cmd_unlock(self,noun,verb,cmdPrefix,cmdSuffix):
		if noun == "***":
			print "I need a Noun too!"
			return False
		if noun != "man":
			print "I can't {0} a {1}".format(cmdPrefix,cmdSuffix)
			return False
		if self.state.currentLocation != 'ladder':
			print "Not now ..."
			return False
		if (self.state.objects['key']['location'] != 'carrying'
                    and self.state.objects['key']['location'] != 'rosebed'):
			print "I need a Key!"
			return False
		if self.state.manholeUnlocked:
			print "It's already unlocked."
			return False
		self.state.manholeUnlocked=True
		print "OK."
		return False;

	def do_cmd_give(self,noun,verb,cmdPrefix,cmdSuffix):
		if noun == "***":
			print "I need a Noun too!"
			return False
		if self.state.currentLocation == 'palace':
			if noun != "med" or self.state.guardIsAdorned:
				print "Not now ..."
				return False
			if self.state.objects['med']['location'] != 'carrying':
				print "I haven't got it."
				return False
			self.state.objects['med']['location'] = ''
			self.state.objects['gua']['location'] = ''
			self.state.guardIsAdorned=True
			self.state.itemsCarried=self.state.itemsCarried-1
			return True
		if self.state.currentLocation != 'ledge':
			print "Not now ..."
			return False
		if noun != "whi" or self.state.ogreQuelled:
			print "I'm dead!"
			self.do_cmd_gameover(noun,verb,cmdPrefix,cmdSuffix)
		if self.state.objects['whi']['location'] != 'carrying':
			print "I haven't got it."
			return False
		self.state.objects['whi']['location'] = ''
		self.state.objects['ogr']['location'] = ''
		self.state.itemsCarried=self.state.itemsCarried-1
		self.state.ogreQuelled=True
		return True

	def do_cmd_kill(self,noun,verb,cmdPrefix,cmdSuffix):
		if noun == "***":
			print "I need a Noun too!"
			return False
		if noun != "gua" and noun != "ogr" and noun != "dwa":
			print "I can't {0} a {1}".format(cmdPrefix,cmdSuffix)
			return False
		if self.state.objects['swo']['location'] != 'carrying':
			print "I need a Sword!"
			return False
		if noun == "dwa":
			if self.state.currentLocation != 'roadbend':
				print "It's not here!"
				return False
			print "OK."
			self.state.dwarfIsDead=True
			self.state.objects['dwa']['description']="dead dwarf"
			self.state.promptEnteringRoom = True
			return True
		if ((noun == "gua" and self.state.currentLocation != 'palace') or
                    (noun == "ogre" and self.state.currentLocation != 'ledge')):
			print "It's not here!"
			return False
		print "He survives my attack,and strikes back!"
		print "I'm dead!"
		self.do_cmd_gameover(noun,verb,cmdPrefix,cmdSuffix)

	def do_cmd_chop(self,noun,verb,cmdPrefix,cmdSuffix):
		if noun == "***":
			print "I need a Noun too!"
			return False
		if self.state.objects['axe']['location'] != 'carrying':
			print "I need an Axe!"
			return False
		if noun != "tre" and noun != "for":
			print "I can't {0} a {1}".format(cmdPrefix,cmdSuffix)
			return False
		if self.state.currentLocation != 'hillside':
			print "It's not here!"
			return False
		print "I find a Secret Path!"
		self.state.location['hillside']['exits'] = (
                        { 'n': 'quarry', 's': 'meadow', 'e': None, 'w': None })
		self.state.objects['for']['description'] += " secret path"
		self.state.promptEnteringRoom = True
		return True

	# the locations database is a dictionary of dictionaries, keyed by the location name
	def init_locations(self):
		self.state.location = {
			'rosebed': { 'description': "in the middle of a Rose Bed", 'exits': { 'n': None, 's': 'garden1', 'e': None, 'w': None }, 'normallyDark': False },
			'garden1': { 'description': "in a Garden", 'exits': { 'n': None, 's': 'lawn', 'e': None, 'w': None }, 'normallyDark': False },
			'lawn': { 'description': "on a wide Lawn", 'exits': { 'n': 'garden1', 's': 'garden2', 'e': 'hugegarden', 'w': None }, 'normallyDark': False },
			'garden2': { 'description': "in a Garden", 'exits': { 'n': 'lawn', 's': None, 'e': None, 'w': None }, 'normallyDark': False },
			'hugegarden': { 'description': "in a huge Garden", 'exits': { 'n': None, 's': None, 'e': None, 'w': 'lawn' }, 'normallyDark': False },
			'pathend': { 'description': "at the end of a path", 'exits': { 'n': 'garden2', 's': 'swampyhole', 'e': None, 'w': None }, 'normallyDark': False },
			'bedchamber': { 'description': "in a Bedchamber", 'exits': { 'n': None, 's': 'attic', 'e': 'kitchen', 'w': None }, 'normallyDark': False },
			'attic': { 'description': "in a dingy Attic", 'exits': { 'n': 'bedchamber', 's': None, 'e': 'gianthall', 'w': None }, 'normallyDark': False },
			'larder': { 'description': "in the larder", 'exits': { 'n': None, 's': 'kitchen', 'e': None, 'w': None }, 'normallyDark': False },
			'kitchen': { 'description': "in the Kitchen", 'exits': { 'n': None, 's': 'gianthall', 'e': None, 'w': 'bedchamber' }, 'normallyDark': False },
			'gianthall': { 'description': "in a Giant Hall", 'exits': { 'n': 'kitchen', 's': 'storeroom', 'e': 'bedroom', 'w': 'attic' }, 'normallyDark': False },
			'storeroom': { 'description': "in a Storeroom", 'exits': { 'n': 'gianthall', 's': None, 'e': None, 'w': None }, 'normallyDark': False },
			'hiddenroom': { 'description': "in a hidden Room", 'exits': { 'n': None, 's': 'vault', 'e': None, 'w': None }, 'normallyDark': False },
			'vault': { 'description': "in a secret Vault", 'exits': { 'n': None, 's': 'bedchamber', 'e': None, 'w': None }, 'normallyDark': False },
			'bedroom': { 'description': "in a Bedroom", 'exits': { 'n': None, 's': None, 'e': None, 'w': 'gianthall' }, 'normallyDark': False },
			'cellar': { 'description': "in a Cellar", 'exits': { 'n': None, 's': None, 'e': None, 'w': None }, 'normallyDark': False },
			'swampyhole': { 'description': "in a swampy hole", 'exits': { 'n': 'pathend', 's': None, 'e': None, 'w': None }, 'normallyDark': False },
			'dampchamber': { 'description': "in a damp Semi-dark Chamber", 'exits': { 'n': None, 's': None, 'e': 'cavern', 'w': None }, 'normallyDark': True },
			'cavern': { 'description': "in an underground Cavern", 'exits': { 'n': None, 's': None, 'e': None, 'w': 'dampchamber' }, 'normallyDark': True },
			'chasm': { 'description': "by a Chasm", 'exits': { 'n': None, 's': None, 'e': None, 'w': None }, 'normallyDark': True },
			'ledge': { 'description': "on a ledge", 'exits': { 'n': None, 's': None, 'e': 'tunnel', 'w': 'sublake' }, 'normallyDark': True },
			'tunnel': { 'description': "in a narrow tunnel", 'exits': { 'n': None, 's': None, 'e': None, 'w': 'ledge'}, 'normallyDark': True },
			'mustycave': { 'description': "in a musty Cave", 'exits': { 'n': None, 's': 'tunnel', 'e': None, 'w': None }, 'normallyDark': True },
			'sublake': { 'description': "by a subterranean Lake", 'exits': { 'n': None, 's': None, 'e': 'ledge', 'w': None }, 'normallyDark': True },
			'canoe': { 'description': "on a Canoe, on the underground Lake", 'exits': { 'n': None, 's': None, 'e': None, 'w': None }, 'normallyDark': True },
			'bysublake': { 'description': "by an underground Lake", 'exits': { 'n': 'deadend', 's': None, 'e': None, 'w': None }, 'normallyDark': True },
			'ladder': { 'description': "on a Ladder", 'exits': { 'n': None, 's': None, 'e': None, 'w': None }, 'normallyDark': True },
			'deadend': { 'description': "at what seems to be a Dead End", 'exits': { 'n': None, 's': 'bysublake', 'e': None, 'w': None }, 'normallyDark': True },
			'emptyroad': { 'description': "on an empty road", 'exits': { 'n': 'roadbend', 's': 'road', 'e': None, 'w': None }, 'normallyDark': False },
			'road': { 'description': "on a road", 'exits': { 'n': 'emptyroad', 's': None, 'e': None, 'w': None }, 'normallyDark': False },
			'roadbend': { 'description': "by a Bend in the Road", 'exits': { 'n': None, 's': 'emptyroad', 'e': None, 'w': 'roadend' }, 'normallyDark': False },
			'roadend': { 'description': "at the end of the Road", 'exits': { 'n': None, 's': None, 'e': 'roadbend', 'w': None }, 'normallyDark': False },
			'meadow': { 'description': "in a sunny Meadow", 'exits': { 'n': 'hillside', 's': None, 'e': 'palace', 'w': 'emptyroad' }, 'normallyDark': False },
			'palace': { 'description': "by a pink palace", 'exits': { 'n': None, 's': 'courtyard', 'e': None, 'w': 'meadow' }, 'normallyDark': False },
			'hillside': { 'description': "on a hillside", 'exits': { 'n': None, 's': 'meadow', 'e': None, 'w': None }, 'normallyDark': False },
			'quarry': { 'description': "in a disused Chalk Quarry", 'exits': { 'n': None, 's': 'hillside', 'e': None, 'w': None }, 'normallyDark': False },
			'courtyard': { 'description': "in the Courtyard  of the Pink Palace", 'exits': { 'n': 'palace', 's': None, 'e': None, 'w': None }, 'normallyDark': False }, 
			'shack': { 'description': "in a tumbledown Shack", 'exits': { 'n': None, 's': 'quarry', 'e': None, 'w': None }, 'normallyDark': False}
		}

	def init_objects(self):
		self.state.objects = {
		        # objects: keyword, description, initial location, carryable flag
			'lad': { 'description': "creaky old LADDER", 'location': 'rosebed', 'carryable': True },
			'spe': { 'description': "SPECTACLES", 'location': 'garden1', 'carryable': True },
			'swo': { 'description': "sharp SWORD", 'location': 'cellar', 'carryable': True },
			'tor': { 'description': "shiny TORCH", 'location': 'larder', 'carryable': True },
			'key': { 'description': "brass KEY", 'location': 'hiddenroom', 'carryable': True },
			'boo': { 'description': "small BOOK", 'location': 'vault', 'carryable': True },
			'med': { 'description': "golden MEDAL", 'location': 'bedroom', 'carryable': True },
			'whi': { 'description': "bottle of WHISKY", 'location': 'swampyhole', 'carryable': True },
			'aqu': { 'description': "rusty AQUALUNG", 'location': 'storeroom', 'carryable': True },
			'box': { 'description': "mirror BOX", 'location': '', 'carryable': True },
			'can': { 'description': "hide CANOE", 'location': 'mustycave', 'carryable': True },
			'axe': { 'description': "lumber AXE", 'location': 'roadend', 'carryable': True },
			'mir': { 'description': "*the magic MIRROR*", 'location': 'shack', 'carryable': True },
			'ros': { 'description': "rosebed", 'location': 'garden1', 'carryable': False },
			'pat': { 'description': "gravel path", 'location': 'garden2', 'carryable': False },
			'pon': { 'description': "deep pond", 'location': 'pathend', 'carryable': False },
			'vis': { 'description': "Sign here says- VISIT THE GREAT CAVERN", 'location': 'hugegarden', 'carryable': False },
			'tap': { 'description': "tapestry", 'location': 'vault', 'carryable': False },
			'pai': { 'description': "painting", 'location': 'bedchamber', 'carryable': False },
			'lar': { 'description': "larder", 'location': 'kitchen', 'carryable': False },
			'win': { 'description': "closed window with a garden beyond", 'location': 'attic', 'carryable': False },
			'pas': { 'description': "passages", 'location': 'gianthall', 'carryable': False },
			'sto': { 'description': "Sign says- STORE THE MIRROR HERE", 'location': 'storeroom', 'carryable': False },
			'bed': { 'description': "4-poster bed", 'location': 'bedroom', 'carryable': False },
			'tr1': { 'description': "trapdoor", 'location': '', 'carryable': False },
			'tra': { 'description': "trapdoor", 'location': 'cellar', 'carryable': False },
			'und': { 'description': "underground stream", 'location': 'cavern', 'carryable': False },
			'str': { 'description': "stream", 'location': 'chasm', 'carryable': False },
			'cha': { 'description': "deep chasm", 'location': 'chasm', 'carryable': False },
			'ogr': { 'description': "drunken ogre", 'location': 'ledge', 'carryable': False },
			'roc': { 'description': "large rock", 'location': 'tunnel', 'carryable': False },
			'wid': { 'description': "wide lake", 'location': 'sublake', 'carryable': False },
			'lak': { 'description': "lake", 'location': 'bysublake', 'carryable': False },
			'sma': { 'description': "small hole", 'location': 'deadend', 'carryable': False },
			'man': { 'description': "manhole", 'location': 'ladder', 'carryable': False },
			'ban': { 'description': "grassy bank", 'location': 'roadend' },
			'dwa': { 'description': "mean-looking dwarf", 'location': 'roadbend' },
			'hed': { 'description': "hedge", 'location': 'emptyroad' },
			'poo': { 'description': "ornamental pool", 'location': 'courtyard' },
			'roa': { 'description': "road-block", 'location': 'road' },
			'sha': { 'description': "deserted shack", 'location': 'quarry' },
			'for': { 'description': "impenetrable forest", 'location': 'hillside' },
			'gua': { 'description': "palace guard", 'location': 'palace' }
		}

	def maybe_read_saved_game(self):
		print 'Play Old or New Game',
		resp = ''
		while resp != 'o' and resp != 'n':
			try:
				resp = raw_input('(O or N)? ')
			except:
				resp = 'n'
		if resp == 'o':
			self.do_cmd_readsavedgame('','loa','','')

	def do_cmd_gameover(self,noun,verb,cmdPrefix,cmdSuffix):
		print 'Game Over.'
		resp = ''
		while resp != 'y' and resp != 'n':
			try:
				resp = raw_input('Play again? ')
			except:
				resp = 'n'
		if resp == 'n':
			sys.exit(0)
		os.execlp(sys.argv[0], sys.argv[0])

	def __init__(self):
		print "		MAGIC MIRROR	\n	by Michael Taylor."
                self.state = SavedState()
		self.init_locations()
		self.init_objects()
		self.maybe_read_saved_game()

	def do_cmd_help(self,noun,verb,cmdPrefix,cmdSuffix):
		print "Gotta figure this one out on yer own..."

	def parse_command_input(self, instr):
		spaceIndex = instr.find(' ')
		if spaceIndex != -1:
			prefix = instr[:spaceIndex]
			suffix = instr[spaceIndex+1:]
		else:
			prefix = instr
			suffix = ''
		verb = (prefix+'***')[:3]
		noun = (suffix+'***')[:3]
		return [ noun, verb, prefix, suffix ]

	def enter_room(self):
		if self.state.promptEnteringRoom:
			self.state.promptEnteringRoom=False
			print "  Press 'RETURN'"
			raw_input(' ')
  
		# Check for dark
		self.state.isDark=False
		if (self.state.location[self.state.currentLocation]['normallyDark'] and
                    (not self.state.torchIsLit or
                     (self.state.objects['tor']['location'] != 'carrying' and
                      self.state.objects['tor']['location'] != self.state.currentLocation))):
			self.state.isDark=True
		if self.state.isDark:
			print "It's too dark to see!"
		else:
			# Print location and any visible items
			print "I'm {0}.".format(self.state.location[self.state.currentLocation]['description'])
			found=False
			for j in self.state.objects:
				if self.state.objects[j]['location'] == self.state.currentLocation:
					found=True;
					break;
			if found:
				print 'Visible Items are:'
				for j in self.state.objects:
					if self.state.objects[j]['location'] == self.state.currentLocation:
						print '  {0}'.format(self.state.objects[j]['description'])
  
			# Print any visible exits
			found=False
			exits=self.state.location[self.state.currentLocation]['exits']
			for e in exits:
				if exits[e]:
					found=True
					break
			if found:
				print 'I can go: ',
				for e in exits:
					if exits[e]:
						print e,
                                print
		print '----------------------'

	def main(self):
		commands = {
			'?**': self.do_cmd_help,
			'h**': self.do_cmd_help,
			'hel': self.do_cmd_help,
			'n**': self.do_cmd_go,
			's**': self.do_cmd_go,
			'e**': self.do_cmd_go,
			'w**': self.do_cmd_go,
			'nor': self.do_cmd_go,
			'sou': self.do_cmd_go,
			'eas': self.do_cmd_go,
			'wes': self.do_cmd_go,
			'q**': self.do_cmd_gameover,
			"qui": self.do_cmd_gameover,
			"wai": self.do_cmd_wait,
			"sav": self.do_cmd_savegame,
			"loa": self.do_cmd_readsavedgame,
			"i**": self.do_cmd_inv,
			"lis": self.do_cmd_inv,
			"inv": self.do_cmd_inv,
			"get": self.do_cmd_get,
			"g**": self.do_cmd_get,
			"tak": self.do_cmd_get,
			"dro": self.do_cmd_drop,
			"d**": self.do_cmd_drop,
			"lea": self.do_cmd_drop,
			"ope": self.do_cmd_open,
			"fol": self.do_cmd_follow,
			"mov": self.do_cmd_move,
			"m**": self.do_cmd_move,
			"rea": self.do_cmd_read,
			"say": self.do_cmd_say,
			"wea": self.do_cmd_wear,
			"cli": self.do_cmd_climb,
			"thr": self.do_cmd_throw,
			"t**": self.do_cmd_throw,
			"loo": self.do_cmd_look,
			"l**": self.do_cmd_look,
			"exa": self.do_cmd_look,
			"swi": self.do_cmd_swim,
			"jum": self.do_cmd_jump,
			"j**": self.do_cmd_jump,
			"go*": self.do_cmd_go,
			"unl": self.do_cmd_unlock,
			"giv": self.do_cmd_give,
			"kil": self.do_cmd_kill,
			"k**": self.do_cmd_kill,
			"cho": self.do_cmd_chop,
			"cut": self.do_cmd_chop
		}

		newRoom=True
		while True:
			if newRoom:
				self.enter_room()
			cmdStr='aga'
			while cmdStr == 'aga':
				try:
					cmdStr = raw_input('Command: ')
				except:
					cmdStr = 'aga'
			noun, verb, cmdPrefix, cmdSuffix = self.parse_command_input(cmdStr)
			if not verb in commands:
				print "I don't understand '{0} {1}'".format(cmdPrefix, cmdSuffix)
			else:
				newRoom = commands[verb](noun, verb, cmdPrefix, cmdSuffix)

if __name__ == '__main__':
	done = False
	while not done:
		game = GameSession()
		done = game.main()
	quit()
