You are on page 1of 13

#COM713 ADVANCED DATA STRUCTURES AND ALGORITHMS#

# This is the source code for the assignment 2. #


# #
# #
#**************************************************************#

import random
import string
# Rooms have items, players can carry items
class item:
'''An object that can be interacted with

Stored in inventories
Again, you could add more attributes to the item class for playability'''
def __init__(self,name,description="",weight=1):
'''Initialization process

includes a name, description, location, and weight.


name: required - used to interact with object
description: optional - displayed when seeing the item, used as the string, should contain
Name
weight: optional - how heavy an item is
'''
self.name=name
self.description=description
self.weight=weight

def __str__(self):
'''String for the object'''
return self.description
# A player can enter a room from any of the compass directions
class room:
''' An object that represents a location in the world

has an inventory of items, exits, and can be associated with playes'''


def
__init__(self,name,description="",items=None,exits='',dialogue='',north=None,south=None,east
=None,west=None):
'''Initialization process

name: required - used in the description of the room, might be used for other features?
items: an inventory object which contains items
exits: optional - a string with the letters 'neswud' representing directions with visible
exits
dialogue: optional - the conversation or monologue printed when the player uses the
'TALK' command
[direction]: optional - the room to this direction (linked list features)
'''
self.name=name
self.description=description
if items == None:
self.inv = inventory("The room",[])
else:
self.inv = items
self.exits="The visible exits are: "
if "n" in exits:
self.exits=self.exits + "North, "
if "s" in exits:
self.exits=self.exits + "South, "
if "e" in exits:
self.exits=self.exits + "East, "
if "w" in exits:
self.exits=self.exits + "West, "
if len(exits)>1:
self.exits=self.exits[:len(self.exits)-2]
self.north=north
self.south=south
self.east=east
self.west=west
self.dialogue = dialogue

def __str__(self):
'''String for object

Combines the name and description'''


return self.name + ":\n" + self.description

def look(self):
'''Method call for looking at the room

Displays the name, description, exits, and inventory'''


print(("You are in the " + self.name + ":\n"))
print((self.description))
print((self.exits))
print((self.inv))

# Represents the current player


class Playe:
'''An object that represents the player

More attributes could be added to represent other things necessary for a Playe'''
def __init__(self,name=''):
'''Initialization process

name: optional - used to interact with Playe


inv: an inventory object which contains items
room: a room object that represents where the Playe is currently
'''
if name == '':
name = 'idonthaveaname'
self.name=name
self.inv = inventory("Your bag",None)
self.room = None
class inventory:
'''An collection of items

Used for Playes and rooms'''


def __init__(self,name='',items=None):
'''Initialization process

name: optional - displays with inventory, can be changed


items: a list of item objects
'''
if name == '':
name = 'BAG'

self.name=name
if items == None:
self.items=[]
else:
self.items=items

def __str__(self):
'''String for inventory

Uses the name of the inventory and the string for each item'''
x = self.name + " contains:\n"
for item in self.items:
x=x+"\t"+item.name + "\n"
return x

def findItem(self,name):
'''Search inventory for a given item

returns the index number or -1 if not found

'''
for i in range(0,len(self.items)):
if self.items[i].name==name:
return i
return -1

def inventory(self):
'''A simple method to clarify the printing of the inventory
'''
print(self)

# Overall game code and logic


class game:
''' An object for actually playing the game

Contains the methods used to interact with the user interface


as well as the methods for controlling the interaction between Playes and rooms and items
'''
def __init__(self,name,person,start,commands):
'''Initialization process

name: required - the name of the game


person: required - the Playe object that represents the player
start: required - the starting room
commands: required - a dictionary of commands that are valid for the game
order: a string that contains the command line instructions recieved
words: a list of strings that contains the parsing of order

'''
self.name = name
self.person = person
self.start = start
self.commands = commands
self.person.room = start
self.order = ""
self.words = []

def play(self):
'''The actual game loop

contains a call to the welcome screen, as well as the basic game loop;
also contains all the calls for functions for commands
'''
self.welcome() # welcome screen
self.see() # Look at first world
self.person.hasPRINTS = False # Set variables to false

validCommand = True # Set flags


self.done = False
# *********************# main command/response loop #****************** #
while(self.done != True):

if(validCommand == True):
self.order=input("Now what, " + self.person.name + "? ")
else:
self.order=input(self.person.name + ", you are confusing!! Please try again. For a list of
commands, type COMMANDS. ")
validCommand = True # reset valid flag #

self.order = self.order.upper() # convert answer to upper case #


self.words = self.order.split() # break answer into words #

# get a valid command


command = self.getCommand(self.words,self.commands)

# compares the number returned to the dictionary of commands to see what needs to be
done
if command==self.commands["HELP"]: self.help()
elif command==self.commands["QUIT"]: self.quit()
elif command==self.commands["TAKE"]: self.take()
elif command==self.commands["GO"]: self.go()
elif command==self.commands["LOOK"]: self.see()
elif command==self.commands["DROP"]: self.drop()
elif command==self.commands["INVENTORY"]:self.inventory()
elif command==self.commands["TALK"]: self.talk()
elif command==self.commands["COMMANDS"]:self.commandList()
else: validCommand=False # Didn't find a valid command, show error

# ************ End of main command/response loop ************ #


def welcome(self):
'''Welcomes a player to the game

This should be changed to contain the storyline for your game!'''


print(("\n"*30)) # clear screen
print('''
Welcome to QUEST, a game of adventure and amusement.\n\n
You may type 'help' or 'commands' for information about the game.\n\n
******************************************************************************
*******\n\n\n\n

You awake with the sun shining in your eyes. Your head hurts\n
and you cannot remember your name or how you got here.\n''')
def commandObject(self,bag):
'''Checks for object

looks for a word in the command array that matches an object in bag
'''
for word in self.words:
index = bag.findItem(word)
if index > -1:
return index
return -1

def getCommand(self,sentence,commands):
'''Used to search a sentence for a valid command

sentence - list of words


commands - dictionary of commands

returns the value from the dictionary'''


for word in sentence:
if word in commands:
if commands[word]>100:
return commands[word]-100
return commands[word]

return -1 # Didn't find a valid command, so return -1.

def commandList(self):
'''Used to display the commands that have been given a value less than 50'''
for word in self.commands:
if self.commands[word]<50:
print(word)
print("These are your basic commands. There are some shortcut")
print("commands that do not appear here, such as 'go n' or 'north' for 'go north'.")
print("There may also be some necessary commands that are not listed, ")
print("which you will have to find yourself.")

def go(self):
'''Command call for 'go'

Looks for a direction then moves in that direction if possible


Needs to be updated to allow other directions!'''

if "NORTH" in self.words or "N" in self.words:


if self.person.room.north != None:
if not self.restrict("N"):
self.person.room=self.person.room.north
else:
return
else:
print("Chasing Santa are we?\n")
return
elif "SOUTH" in self.words or "S" in self.words:
if self.person.room.south != None:
if not self.restrict("S"):
self.person.room=self.person.room.south
else:
return
else:
print("Joining the migration?\n")
return
elif "WEST" in self.words or "W" in self.words:
if self.person.room.west != None:
if not self.restrict("W"):
self.person.room=self.person.room.west
else:
return
else:
print("In case you didn't get the memo, the gold rush was over decades ago.\n")
return
elif "EAST" in self.words or "E" in self.words:
if self.person.room.east != None:
if not self.restrict("E"):
self.person.room=self.person.room.east
else:
return
else:
print("Chasing the sunrise?\n")
return
else: # Didn't find a legal direction
print("I'm sorry, you can't teleport.\n")
return
self.see()
def help(self):
'''Prints out the help message

Be sure to edit this to work with your game, doesn't need to contain all commands, just basics
'''

print("\n\n****************************************************")
print("Quest is an Adventure game. It allows you to visit")
print("many places and get rewards in the form of treasures ")
print("and experience. You will be given a score when your ")
print("adventure is over or you may use the 'STATS' command")
print("to find your present score.\n")
print("Some commands are 'TAKE' 'QUIT' 'GO' 'HELP' 'COMMANDS'\n")
print("Commands take the form of: <verb> <noun>")
print("For example: 'go north' , 'go south' or 'help me' ")
print(" or 'Let's go to the north for a while.' \n")
print("Good luck, you'll need it !!\n")
print("****************************************************")

def inventory(self):
'''Command call for inventory

Calls the inventory function of the player's bag'''


self.person.inv.inventory()

def talk(self):
'''Command call for talk
calls the dialogue embedded in the room
if none, includes an error message'''

if self.person.room.dialogue != '':
print("\n")
if self.person.room.name == 'Corridor_North':
index = self.person.inv.findItem("CHIPS")
if index == -1:
print(self.person.room.dialogue)
else:
print("Thank you so much for the chips! Let me help you with any fingerprint
locks.\n\nMy name's Finlay, by the way.\n")
del self.person.inv.items[index]
self.person.hasPRINTS = True
else:
print(self.person.room.dialogue)
else:
print("\nLONEEEEEEEEEEELY\nI'M MISTER LONLEEEEEEEEEEEY\n")

def kill(self, reason):


'''Ends the game and displays the reason'''
self.done = True

print("\n\n=========================================================\n\n")
print((reason + " \n"))

print("\n=========================================================\n")
def quit(self):
'''Player has chosen to quit, make sure they really want to, then do it!
'''
ans = input("Are you sure you want to quit")
if ans.upper()[0] == 'Y':
self.done = True
print("\n\nBye! \n")
else:
print("\n\n Good Choice, Don't be a Wimp!!\n")

def restrict(self,direction):
'''Checks specific restrictions on movement

any traps or special rules for movement in a given room


should be placed here.

Uses the name of the current room and the direction to check for restrictions.'''

if (self.person.room.name == "Misson_Starts" and direction == "W"):


if self.person.inv.findItem("LOCKPICK") == -1:
print("\nYou bang your head against the bars.\nThat's not going to get you anywhere.\n")
return True
elif (self.person.room.name == "Corridor_South" and direction == "S"):
if self.person.hasPRINTS != True:
print("\nI wouldn't try it without a good fingerprint\n")
return True
elif (self.person.room.name == "Break_Room" and direction != "N"):
print("\ncapture message\n\n\n\n")
return False
return False

def see(self):
'''Command call for "see"

Displays current surroundings'''

print((self.person.room.description))
print((self.person.room.inv))
def take(self):
'''Command call for "take"

Looks for an item in the room, then picks it up and places in


person's inventory'''
index = self.commandObject(self.person.room.inv) # Checks to see if you've asked for a
legitimate item

if index == -1:
print("\nI don't see that anywhere!\n")
return
elif self.person.room.inv.items[index].weight == 10000:
# 10000 is used to show that an item can't be picked up
print(("\nThe " + self.person.room.inv.items[index].name + " seems to be attached.\n"))
else:
self.person.inv.items.extend([self.person.room.inv.items[index]])
print(("\nYou now have a " + self.person.room.inv.items[index].name + ".\n"))
del self.person.room.inv.items[index]

def drop(self):
'''Command call to drop

Looks for the specified item in the player's inventory, then places it in the room'''

index = self.commandObject(self.person.inv) # Checks to see if you've asked for a legitimate


item

if index == -1:
print("\nYou aren't holding that\n")
return
else:
self.person.room.inv.items.extend([self.person.inv.items[index]])
print(("\nYou dropped your " + self.person.inv.items[index].name + ".\n"))
del self.person.inv.items[index]

#***********************************************************************#
# Initialize:: Load the commands, rooms, players, and worlds. (daw) 2/28/06
#***********************************************************************#
def Initialize():
'''Sets up the world, fills the rooms, creates the items, player, and commands

All setup and creation things are done here, outside the classes'''

# --------------------- Load valid command table -------------------- #


# all commands must be in this dictionary
# commands greater than 100 are shortcut commands, need the 100 to be subtracted for use
# this is done to keep the command list relatively short
commands = { 'HELP' : 1,
'QUIT' : 2,
'Q' : 102,
'TAKE' : 3,
'GET' : 103,
'COMMANDS' : 4,
'GO' : 5,
'SOUTH' : 105,
'NORTH' : 105,
'EAST' : 105,
'WEST' : 105,
'UP' : 105,
'DOWN' : 105,
'LOOK' : 6,
'SEE' : 106,
'DROP' : 7,
'INVENTORY' : 8,
'INV' : 108,
'TALK' : 9,
}

# --------------------------------------------------------------------- #
# --------------------- Load rooms -------------------- #
# creation of items in each world
# and the rooms

world = [] # create a list for all the rooms

#room 0

stuff = inventory("room",[
item("KNIFE","A KNIFE with a knote saying, 'You're welcome!'",3)
])
world.append(room("Misson_Starts","You find yourself in a drab prison cell\nThere are iron
bars in the west separating you from a corridor\n and a toilet in the middle",stuff,"w"))
#room 1
stuff = inventory("room",[
item("LOCKPICK","A LOCKPICK with a note saying, 'You're welcome!'",3)
])
world.append(room("Toilet","Reaching down in the suprisingly clean toilet,\nyou feel
something.",
stuff,"n",north=world[0]))
#room 2
world.append(room("Corridor_Middle","You are in the middle section of a short prison
hallway.\nThere appears to be another cell like yours\nto the west, and more parts of the\ncorridor
to the north and south.\nAbove your cell door, there is a sign that reads:\nTEST SUBJECT
013489",
None,"nsw",east=world[0]))
#room 3
world.append(room("Corridor_North","You are in the north section of the corridor,\nWith cells
to the east and west.\nThere is a buff officer, but he hasn't seen you.\nYET",
None,"ew","Okay, you managed to escape. I'm impressed. You know, I should report
you, but I've heard there's some good chips going around the cells...",south=world[2]))
#room 4
world.append(room("Corridor_South","You are in the south section of the corridor.\nThere are
cells to the east and west, and a door\nwith a fingerprint lock.",
None, "n",north=world[1]))
#room 5
world.append(room("Cell_NE","You are in a cell with a prisoner. There is\na window with bars
you could cut\nto the east.",
None, "e",west=world[3]))
#room 6
stuff = inventory("room",[item("CHIPS","A bag of potato CHIPS",1)])
world.append(room("Cell_SE","You are in a cell much like your
own.",stuff,"w",west=world[4]))

#room 7
world.append(room("Cell_NW","You are in a cell much like your own.","e",east=world[3]))

#room 8
world.append(room("Cell_W","You are in a cell much like your own.","e",east=world[2]))

#room 9
world.append(room("Cell_SW","You are in a cell much like your own.","e",east=world[4]))

#room 10
world.append(room("Break_Room","\nYou are in a rather large room with a ping-pong\ntable
in the middle and a bunch of chairs and tables scattered\nthroughout the room, all empty.\n There
are doors to the east, west, and south.\nThe ones to the east and west both have prison
corridors\nand the one to the south is the administration office.\n",
"n",north=world[4]))

#room 11
world.append(room("Solitary","\nIt's too dark to see anything.\n"))

#room 12
world.append(room("Upper_Solitary","\nClimbing up the rough walls, you manage to make
your way to the ceiling.\nSuddenly there is a massive explosion, blowing the roof down to the
ground\nA familiar face pokes out of the gaping hole.\nYou:'Finlay!'\nFinlay:'Come on, let me
help you up.'\n"))

#room 13
world.append(room("End","\nYOU ESCAPED\nPART ONE COMPLETE\nYou win!\n"))

# --------------------- Finish room connections -------------------- #


world[0].west = world[2]
world[0].south= world[1]
world[2].north = world[3]
world[1].south = world[4]
world[2].west = world[8]
world[3].east = world[5]
world[3].west = world[7]
world[4].east = world[6]
world[4].west = world[10]
world[4].south = world[10]
world[10].east = world[11]
world[11].North = world[12]
world[12].North = world[13]

# --------------------- Load player and game -------------------- #

player = Playe("Owain")

# ---- return the game structure which now contains all aspects --- #
return game("Fibbon",player,world[0],commands)

quest = Initialize() # Load the structures of places to visit #


quest.play()

# So the program doesn't just close!


pause = input("Press Enter to continue")

You might also like