I'm really stuck on this simple user input game I created. It's an exercise from learn python the hard way. I've been trying for over a week to figure it out on my own and finally caved in to asking for help. I think the problem point in my code is the Engine() class. Anyway here's the code:
from sys import exit
from random import randint
class Island(object):
def enter(self):
pass
class Engine(object):
def __init__(self, island_map):
self.island_map = island_map
def play(self):
current_island = island_map.opening_island()
last_island = self.island_map.next_island('Tropical')
while current_island != last_island:
next_island_name = current_island.enter()
current_island = self.island_map.next_island(next_island_name)
current_island.enter()
class Loser(Island):
snippets = ["Welcome to loser Island",
"Can't win them all",
"There's always next time"]
def enter(self):
print "Game over"
print Loser.snippets[randint(0,len(self.snippets)-1)]
exit(1)
class Jungle(Island):
def enter(self):
print "Welcome to the Jungle!"
print "You must fight the monkey to pass!"
print "Choose your weapon..."
weapons = ['stick', 'fly swatter', 'banana']
print weapons
fighter_weapon = raw_input("Choose from a a weapon above...")
if fighter_weapon == 'stick':
print "Stick can't beat a monkey!"
print "Monkey wins"
return 'Loser'
elif fighter_weapon == 'fly swatter':
print "The monkey steals your fly swatter"
print "Monkey wins"
return 'Loser'
elif fighter_weapon == 'banana':
print "The monkey is hypnotized by the banana"
print "You continue to the next island..."
return 'Frozen'
else:
print "What? Doesn't make sense"
return 'Jungle'
class Frozen(Island):
#add green, blue circle, and black diamond
def enter(self):
print "This is snow land"
print "Here's your snowboard, choose your path"
print "([[[[[[[[[)"
runs = ["green", "blue", "black"]
print runs
run_choice = raw_input(" >")
if run_choice == 'green':
print "Easy way out?"
print "No good"
print "Wrong"
return 'Loser'
elif run_choice == 'blue':
print "okay, at least not the easiest way"
print "You have some guts, I'll let you choose one more time"
return 'Frozen'
elif run_choice == 'black':
print "I like your style"
print "Going for the hard choice shows courage"
print "Continue to the next island"
return 'Tropical'
else:
print "Say whaaat?!"
return 'Frozen'
class Tropical(Island):
def enter(self):
print "You made it to the final Island!"
print "Look here's the treasure chest!"
print " All that's left to do is guess the code on the chest"
print "Be smart, you only get five guesses..."
t_key = "1234"
chest_guess = raw_input("What do you think it is?")
guesses = 0
while chest_guess != t_key and guesses < 4:
print "Guess again"
guesses += 1
chest_guess = raw_input(" ?")
if chest_guess == t_key:
print "You guessed right!"
print "You won"
else:
print "Sorry"
return 'Loser'
class Map(object):
islands = {
'Loser': Loser(),
'Jungle': Jungle(),
'Frozen': Frozen(),
'Tropical': Tropical(),
}
def __init__(self, start_island):
self.start_island = start_island
def next_island(self, island):
val = Map.islands.get(island)
return val
def opening_island(self):
return self.next_island(self.start_island)
mj_map = Map('Jungle')
mj_game = Engine(mj_map)
mj_game.play()
Right now I'm stuck on an error that states "island_map" is not defined in my Engine class. Which I don't understand because to me it looks like it is defined. Any input would be appreciated.
def play(self):
current_island = island_map.opening_island()
needs to be changed to
def play(self):
current_island = self.island_map.opening_island()
as it is apart of that instance
Related
def equip(x):
global bag_sword
global bag_chest
global bag_gloves
global bag_helmet
while x == "iron sword" and "iron sword" in bag:
if bag_sword:
print "You can't have 2 weapons equipped!"
x = ""
print "\nYou equip the iron sword.\n"
bag.remove("iron sword")
bag_sword.append("iron sword")
When I run this the first time, it works fine, but when I run it a second time nothing happens.
bag_sword is a list
test code:
bag.append("iron sword")
if input1[:5] == "equip":
print input1[:5]
equip(input1[6:])
print input1[6:]
I type into the console 'equip iron sword'
I've tried using a variable in place of the input[]
(It isn't syntax)
Here is how you can make the function work as described:
bag_sword = []
def equip(x):
global bag_sword
if x == "iron sword":
if "iron sword" in bag_sword:
print "You can't have 2 weapons equipped!"
else:
bag_sword.append("iron sword")
print bag_sword # Prints "[]".
equip("iron sword") # Prints nothing. Puts the string "iron sword" in bag_sword.
print bag_sword # Prints "['iron sword']".
equip("iron sword") # Prints "You can't have 2 weapons equipped!". bag_sword is unchanged.
You can make nwk's solution more general (also try to get rid of global variables):
def equip(item, bag):
if item in bag:
print "You can't have 2 {}s equipped!".format(item)
else:
bag.append(item)
def main():
bag_sword = []
print bag_sword
equip("iron sword", bag_sword)
print bag_sword
equip("iron sword", bag_sword)
if __name__ == '__main__':
main()
It also seems to me that a dictionary or class would be a better alternative than several bag lists:
def equip(item, slot, inventory):
if inventory[slot] == item:
print 'Already equipped.'
else:
inventory[slot] = item
print item.capitalize(), 'equipped.'
def main():
inventory = {
'weapon': None,
'gloves': None,
}
equip('iron sword', 'weapon', inventory)
print inventory
equip('iron sword', 'weapon', inventory)
if __name__ == '__main__':
main()
ERROR: Line 29, in Map 'empty_room' :
I have tried rewriting my classes and other small things and have not been able to come up with any solutions. My indentations are correct(or so they seem) on notepad++ they just didn't transfer over very well to SOF. Any troubleshooting is appreciated:) THANK YOU!!
P.S. I am learning on my own with the book 'Learn Python the Hard Way' and I am doing an exercise to make a game similar to zork. Hope this helps.
from sys import exit
class Scene(object):
def enter(self):
print "This scene is not configured"
exit(1)
class Engine(object):
##calling Engine(x) x is the mapScene
def __init__(self, mapScene):
self.mapScene = mapScene
def play(self):
currentScene = self.mapScene.openingScene()
while True:
print "\n-------------------"
nextSceneName = currentScene.enter()
currentScene = self.mapScene.nextScene(nextSceneName)
class Map(object):
scenes = {
'empty_room': EmptyRoom(),
'living_room': LivingRoom(),
'office': Office(),
'hallway': Hallway(),
'kitchen': Kitchen(),
'master_bedroom': MasterBedroom(),
'kids_bedroom': KidsBedroom(),
'attic': Attic()
}
##when calling Map(x) x is the startscene
def __init__(self, startScene):
self.startScene = startScene
##When calling nextScene(x) x is the sceneName
def nextScene(self, sceneName):
return Map.scenes.get(sceneName)
##????
def openingScene(self):
return self.nextScene(self.startScene)
class EmptyRoom(Scene):
def enter(self):
print ""
action = raw_input("> ")
if action == "open door":
return 'living_room'
class LivingRoom(Scene):
def enter(self):
print ""
action = raw_input("> ")
if action == "kitchen":
return 'kitchen'
elif action == "stairs" or "go upstairs":
print "The steps creek as you ascend to the unknown..."
print "Are you sure you want to go up here?"
action = raw_input("> ")
if action == "yes" or "kinda":
return 'hallway'
else:
return 'living_room'
elif action == "empty room":
return 'empty_room'
else:
return 'living_room'
class Kitchen(Scene):
def enter(self):
print ""
action = raw_input("> ")
if action == "office" or "go right":
return 'office'
elif action == "living room":
return 'living_room'
else:
return 'kitchen'
class Office(Scene):
def enter(self):
print ""
action = raw_input("> ")
if action == "kitchen":
return 'kitchen'
class MasterBedroom(Scene):
def enter(self):
print ""
action = raw_input("> ")
if action == "hallway":
return 'hallway'
class KidsBedroom(Scene):
def enter(self):
print ""
action = raw_input("> ")
if action == "hallway":
return 'hallway'
class Hallway(Scene):
def enter(self):
print ""
action = raw_input("> ")
if action == "downstairs" or "stairs" or "living room":
return 'living_room'
elif action == "bedroom" or "master bedroom" or "left":
return 'master_bedroom'
elif action == "kids room" or "kids bedroom" or "right":
return 'kids_bedroom'
elif action == "pull string":
print"You have just opened the attic staircase would you like to go up?"
action = raw_input("> ")
if action == "yes":
return 'attic'
elif action == "no" or "nope":
return 'hallway'
else:
print "I wouldn't have went either\n"
print "SMASH, the attic door springs shut\n"
return 'hallway'
else:
return 'hallway'
class Attic(Scene):
def enter(self):
print ""
action = raw_input("> ")
if action == "downstairs" or "hallway":
return 'hallway'
aMap = Map('empty_room')
aGame = Engine(aMap)
aGame.play()
The class definition should come first before it is used.
class EmptyRoom(Scene):
def enter(self):
print ""
action = raw_input("> ")
if action == "open door":
return 'living_room'
class Map(object):
scenes = {
'empty_room': EmptyRoom(),
...
}
Same for LivingRoom, Office, Hallway, Kitchen, MasterBedroom, KidsBedroom, Attic.
The definition of scenes inside Map is run when the class is being built, not when you later call the class to instantiate it. At that time, EmptyRoom doesn't exist yet - Python works from the top of your code down, so EmptyRoom only exists after it has reached the end of the indented block underneath class EmptyRoom:. So for this to work, Map needs to go after all of your other classes rather than before.
Ok I going through LPTHW and writing a game. We are supposed to section the game up into different scripts to see how importing them works. I have 4 scripts: ex45.py executes the main code, Engine45.py is the engine, Locations45.py is the list of locations, and Maps45.py is what holds the map values and moves through locations.
The error I get when running is:
Traceback (most recent call last):
File "ex45.py", line 2, in
import Maps45
File "C:\Users\Raistlin\Python\Maps45.py", line 1, in
import Locations45
File "C:\Users\Raistlin\Python\Locations45.py", line 4, in
class Map(object):
File "C:\Users\Raistlin\Python\Locations45.py", line 6, in Map
'Gold_gym' : Gold_gym(),
NameError: name 'Gold_gym' is not defined
I don't understand why I am getting a Gold_gym is not defined when it is defined in Locations45.py.
Code blocks below:
ex45.py
import Engine45
import Maps45
import Locations45
a_map = Map('Gold_gym')
a_game = Engine(a_map)
a_game.run()
Engine45.py
class Engine(object):
def __init__(self, location_map):
print "Engine __init__ has location_map", location_map
self.location_map = location_map
def run(self):
current_location = self.location_map.opening_location()
print "Play's first scene", current_location
while True:
print "\n"('-' * 20)
next_location_name = current_location.use()
print "next location", next_location_name
current_location = self.location_map.next_location(next_location_name)
print "map returns new location", current_location
Locations45.py
from random import randint
from sys import exit
class Location(object):
def use(self):
print "This is not configured."
exit(1)
class Loser_gym(Location):
quips = [
'You are worthless, goodbye.'
'Thanks for trying noob.'
'Sex and candy, not today.'
]
def use(self):
print Loser_gym.quips[randint(0, len(self.quips)-1)]
exit(1)
class Gold_gym(Location):
def use(self):
print "Welcome to the Gold Gym. This gym will test your physical prowess."
print "Before you there is a large pool of water with a center platform."
print "On your person is a satchel, a whip, a hat, and a gun."
print "Your goal is to find the way out of the gym."
print "Acceptable inputs are satchel, whip, hat, or gun."
print "Good Luck."
action = raw_input("What do you do:> ")
if action == 'satchel':
print "You throw your satchel towards the center platform."
print "It does absolutely nothing. Try again."
return 'Gold_gym'
elif action == 'whip':
print "You use your whip somewhat akin to Indiana Jones."
print "You swing from a pipe and land squarely on the center platform."
print "You have survived this turmoil."
return 'Sapphire_gym'
elif action == 'hat':
print "You valiantly toss your hat toward the center platform."
print "Your hat is caught by a gust of wind and blows away."
print "You cannot survive without your hat."
return 'Loser_gym'
elif action == 'gun':
print "You shoot your about wildly in the air."
print "A ricochet hits you in the head and you die."
return 'Loser_gym'
else:
print "DOES NOT COMPUTE, TRY AGAIN."
return 'Gold_gym'
class Sapphire_gym(Location):
def use(self):
print "Welcome to the Sapphire gym, here your cognitive ability will be tested."
print "Just kidding there is no way to figure this out consistently."
print "Before you stands a door, the door has a small keypad on it."
print "Below the keypad is what appears to be a smart card reader."
print "On your way to the location you picked up two smartcards off the ground."
print "One is red and one is green."
print "Clearly you will need to use a smartcard and guess a code(3-digits)."
card = raw_input('Which card do you choose:> ')
if card == 'red':
print "A laser beam comes out of the door and cauterizes your brain."
return 'Loser_gym'
elif card == 'green':
code = '%d%d%d' % (randint(0,9), randint(0,9), randint(0,9))
guess = raw_input('What code do you enter:> ')
guesses = 0
while guess != code and guesses < 20 and guess != '123':
print "INCORRECT!"
guesses += 1
guess = raw_input('What code do you enter:> ')
if guess == code or guess == '123':
print "Nice guess noob! You may press onward."
return 'Cerulean_gym'
else:
print "WRONG! TOO MANY GUESSES! DIE INFERIOR BEING!"
return 'Loser_gym'
class Cerulean_gym(Location):
def use(self):
print "Welcome to the final gym, the Cerulean Gym!"
print "Before you is a 3x3 platform, your job is to cross the platform."
print "Be warned that each tile can trigger a trap."
print "Good luck!"
correct_square = ['3', '1', '2']
jump = raw_input("Square 1, 2, or 3?:> ")
jumps = 0
while jumps < 3:
if jump == correct_square:
print "Nice job! You picked the correct square!"
jump += 1
correct_square = correct_square[0+jump]
jump = raw_input("Square 1, 2, or 3?:> ")
jumps += 1
else:
print "YOU FAIL! Goodbye you puny infidel."
return 'Loser_gym'
print 'NICE JOB. YOU WIN ALL THE BASE!'
Maps45.py
import Locations45
class Map(object):
locations = {
'Gold_gym' : Gold_gym(),
'Sapphire_gym' : Sapphire_gym(),
'Cerulean_gym' : Cerulean_gym(),
'Loser_gym' : Loser_gym()
}
def __init__(self, start_location):
self.start_location = start_location
print "start_location in __init__", self.start_location
def next_location(self, location_name):
print "start_location in next_location"
val = Map.locations.get(location_name)
print "next_location returns", val
return val
def opening_location(self):
return self.next_location(self.start_location)
Help please?
When you:
import Locations45
that module is imported under the namespace Locations45
So when you call
Gold_gym()
It looks in Maps45 for that object, never knowing to look in Locations45.
Change the line to read:
locations = {
'Gold_gym' : Locations45.Gold_gym(),
'Sapphire_gym' : Locations45.Sapphire_gym(),
'Cerulean_gym' : Locations45.Cerulean_gym(),
'Loser_gym' : Locations45.Loser_gym()
If you just do import Locations45, it doesn't import each of the names - instead, it imports it as a group. You can refer to individual things within the group using a period:
'Gold_gym': Locations45.Gold_gym(),
'Sapphire_gym': Locations45.Sapphire_gym(),
'Cerulean_gym': Locations45.Cerulean_gym(),
'Loser_gym': Locations45.Loser_gym()
Alternatively, you could import all of the names specifically:
from Locations45 import Gold_gym, Sapphire_gym, Cerulean_gym, Loser_gym
which would make those names available without needing to use the prefix.
I am making a small text game, and one of my methods is behaving unexpectedly, and I can't figure out why. If I import the module and run the method in python, it works fine. Some parts of the game aren't complete, but that parts that I need run fine.
With the module pasted below, choose method is changing a list into a string, but only when the module is run. I'm running this on 2.7.3, on a mac.
Edit: I figured it out. The program execution had continued, and I was confused by the choose call in the match method. The options parameter sent in match was a string, instead of the list it should have been, but that was simple to figure out why.
import fighters
import weapons
from random import randint
from sys import exit
class Hero(object):
weapons = ["spikeglove", "shortsword"]
hp = {"actual":50, "base":50}
score = 0
def attack(self, weapon, method):
return None
class Scene(object):
# Returns one or more items from the provided choices
def choose(self, options, max_choices, prompt):
chosen = []
while len(chosen) < max_choices and len(options) > 0:
print
print prompt
print options, chosen
for o in options:
print "- {}".format(o)
print type(options)
choice = raw_input("> ")
if choice in options:
chosen.append(choice)
options.remove(choice)
print options, chosen
else:
print "That is not one of the options!"
if len(chosen) == 1:
return chosen[0]
else:
return chosen
class Death(Scene):
def enter(self):
print "You are now dead"
return "menu"
class Exit(Scene):
def enter(self):
print "Thanks for playing!"
return exit(1)
class Menu(Scene):
def enter(self):
menu_options = ["play", "train", "exit"]
choice = self.choose(menu_options, 1, "Welcome to the Arena!")
return choice
class Level(Scene):
def __init__(self):
self.prologue = "Welcome to {}".format(self.__class__.__name__)
next_scene = "level1"
# A match is the fight between the Hero and a particular Enemy
# A Hero must defeat each Enemy via a match to win the tournament/level
def match(self, hp, weapons, enemy):
hero_hp = hp
enemy_hp = enemy.stats["hp"]
last_attack = ""
while hero_hp and enemy_hp:
weapon_choice = self.choose(weapons, 1, "> ")
attack_choice = self.choose(weapon_choice.available_attacks(last_attack), 1, "> ")
last_attack = attack_choice
hero_attack = hero.attack(attack_choice)
enemy_attack = enemy.attack()
print "Hero: {} {}: {}".format(hero_hp, enemy, enemy_hp)
if hero_hp:
return "victory", hero_hp
else:
return "defeat"
# The game cycles through the enemies that our hero has to face
# passing the setup to the "match" function for the fighting
def enter(self):
print
print
print self.prologue
start_hp = hero.hp['actual']
weapons = self.choose(hero.weapons, 2, "Choose a weapon")
while self.enemies:
enemy = fighters.roster[self.enemies.pop()]
match_outcome, finish_hp = self.match(start_hp, weapons, enemy)
if match_outcome == "defeat":
hero.hp['actual'] = hero.hp['base']
return "death"
# The Hero enters the next match with the current HP obtained from the previous match
start_hp = finish_hp
# Add our Hero's victory points, and get them some medical attention
# before heading back to the Barracks
points_award = 5
hero.points += points_award
hero.hp['actual'] = hero.hp['base']
new_weapon = "shortsword"
hero.add_weapon(new_weapon)
epilogue = """Congratulations!
You have gained {} points for a total score of {}.\n
You have unlocked the \"{}\" """.format(
points_award, hero.points, new_weapon)
return next_scene
class Train(Scene):
pass
class Level1(Level):
enemies = ["boxer", "boxer"]
next_scene = "level2"
class Level2(Level):
pass
class Level3(Level):
pass
class Level4(Level):
pass
class Level5(Level):
pass
class Engine(object):
def __init__(self, start_scene):
self.start_scene = start_scene
scenes = {
"menu": Menu(),
"death": Death(),
"exit": Exit(),
"play": Level1(),
"level2": Level2(),
"level3": Level3(),
"level4": Level4(),
"level5": Level5(),
}
def next_scene(self, scene_name):
return self.scenes[scene_name]
def play(self):
current_scene = self.scenes[self.start_scene]
while True:
next_scene = current_scene.enter()
current_scene = self.scenes[next_scene]
if __name__ == "__main__":
hero = Hero()
game = Engine("menu")
game.play()
Terminal output:
$ python arena.py
Welcome to the Arena!
['play', 'train', 'exit'] []
- play
- train
- exit
<type 'list'>
> play
['train', 'exit'] ['play']
Welcome to Level1
Choose a weapon
['spikeglove'] []
- spikeglove
<type 'list'>
> spikeglove
[] ['spikeglove']
>
spikeglove []
- s
- p
- i
- k
- e
- g
- l
- o
- v
- e
<type 'str'>
Yet when I run in python:
>>> import arena
>>> s = arena.Level1()
>>> s.choose(['shortsword', 'spikeglove'], 2, "Choose a weapon")
Choose a weapon
['shortsword', 'spikeglove'] []
- shortsword
- spikeglove
<type 'list'>
> shortsword
['spikeglove'] ['shortsword']
Choose a weapon
['spikeglove'] ['shortsword']
- spikeglove
<type 'list'>
> spikeglove
[] ['shortsword', 'spikeglove']
['shortsword', 'spikeglove']
The if __name__ == "__main__": means that the portion of code indented after that if-statement will be executed only when the script is executed, not when it is imported.
I'm making a python text adventure. It is based off of ex41 in Learn Python the Hard Way, so it is somewhat similar. My question, however, has nothing to do with that exercise. I'm trying to make an inventory so that an item can be picked up and used (i.e. a key or febreeze).
At first my plan was to use a Boolean variable so that when the item was 'picked up' it would set a value to True, but it doesn't seem to be working. I think that the problem is that the value resets once I leave the room.
Now I'm trying a list and when the item is 'picked up' the item is appended into the inventory list.
How can I make an inventory, or at least 'pick up' an item and then later 'use' it?
The lines of code that I think are important to look at are 18-20 (under the def __init__(self, start)), 77(under the def cell(self)), 161-162(under the def janitor(self)).
from sys import exit
from random import randint
import time
prompt = '> '
class Game(object):
def __init__(self, start):
self.quips = [
"Way to go, you died."
"Now you're dead. Sweet.",
"Well isn't this just peachy? You're dead. (It's not peachy.)"
]
self.start = start
#self.smell = 0
#self.Febreeze = False
#self.key = False
self.inventory = []
#if self.smell >=2:
# return 'death'
def play(self):
next = self.start
while True:
print "\n-------"
room = getattr(self, next)
next = room()
def death(self):
print self.quips[randint(0, len(self.quips)-1)]
exit(1)
def intro(self):
print "You wake up."
print "You're in a dark cell."
print "You have no idea who you are or where you are."
print "The door is slightly open."
print "You stagger through the door. The light is blinding."
print "You have just escaped imprisonment and you're on the run."
return 'central_corridor'
def central_corridor(self):
print "In front of you is a long corridor with no doors on the side, but you think you can make out a door at the very end."
print "Behind you is the cell that you have just escaped."
next = raw_input(prompt)
if "cell" in next:
print "You decide to go back into your cell."
return 'cell'
elif "forward" in next:
print "You travel down the corridor towards the door."
return 'front_corridor'
else:
print "That command doesn't exist."
return 'central_corridor'
def cell(self):
print "You're standing in the middle of a musty cell."
print "There is a bed in the corner with a rotting mattress."
print "Under the bed the bricks are loose."
print "In the opposite corner there is a dirty toilet that implies that prison food is even worse than Taco Bell."
print "There are some scratches on the wall next to the toilet."
print "Behind you is an exit into the corridor."
next = raw_input(prompt)
if "toilet" in next:
print "It'd probably be best if this toilet wasn't described."
#self.smell = self.smell + 1
return 'cell'
elif "febreeze" in next and "Febreeze" in self.inventory #and self.Febreeze = True:
print "You use the Febreeze on the toilet to get rid of the odor."
print "Now you can go behind the toilet to read the rest of the scratches."
elif "scratches" in next:
print "The scratches on the wall seem to be tally marks. It goes up to 123. I wonder what it means."
print "You see more scratches behind the toilet, but the stench is too much for you to handle."
print "If only you could get rid of the smell..."
#self.smell = self.smell + 1
return 'cell'
elif "bed" in next:
print "There are various stains on the mattress. Some of the springs are poking up into the mattress. Ouch."
print "Buried between the wall and the mattress is a stuffed animal."
return 'cell'
elif "bricks" in next:
print "You pull the bricks out of the floor and find a few pieces of toilet paper."
print "There is a note written on them in what you hope is dried blood."
print "The note reads:\n -------------------------\nthe closet!! the closet in the walls i'm not \nsure\twhich one it is but its defin-\nly in the hall. i hear it in the bricks!\n---------------------------"
print "Hmm, maybe it's a hint or something."
elif "corridor" in next:
return 'central_corridor'
else:
print "I do not understand how to %s" % next
return 'cell'
def front_corridor(self):
print "You are standing in front of a door."
print "On the side of the door is a keypad."
next = raw_input(prompt)
if "keypad" in next:
return 'keypad'
elif "wall" in next:
return 'wall'
elif "back" in next:
return 'central_corridor'
else:
print "I don't understand %s" % next
return 'front_corridor'
def wall(self):
print "Which wall do you want to check?"
next = raw_input(prompt)
if "left" in next:
return 'left'
elif "right" in next:
return 'right'
elif "back" in next:
return 'front_corridor'
def right(self):
print "You examine the wall carefully, running your fingers across each of the bricks."
print "Unfortunately it doesn't look like anything of value is in this wall."
print "Well, you just wasted some time."
return 'wall'
def left(self):
print "You examine the wall carefully, running your fingers across each of the bricks."
print "One of the bricks seems to be protruding from the wall."
print "Do you push it?"
next = raw_input(prompt)
if next[0] == "y":
print "A few of the bricks shift, revealing a secret door way."
return 'janitor'
elif next[0] == "n":
print "You decide not to push the brick. Good thinking, it may have been a booby trap."
return 'front_corridor'
else:
print "That doesn't exactly make sense..."
return 'wall'
def janitor(self):
print "You are in a room filled with janitorial tools."
print "On your left you see a few cans of Febreeze, a plunger and a Playboy magazine."
next = raw_input(prompt)
if "febreeze" in next:
print "You pick up some Febreeze and put it in your back pocket."
print "Maybe this will be useful somewhere down the line."
self.inventory.append("Febreeze")
#self.Febreeze = True
return 'janitor'
elif "plunger" in next:
print "You try to pick up the plunger but it appears to be stuck in the ground."
print "After tugging for a few minutes the handle comes out, leaving the rubber suction cup plastered to the floor."
print "Who knows what's keeping it there."
print "You decide not to touch it."
return 'janitor'
elif "playboy" in next:
print "Well isn't that nice."
print "These janitors certainly have good taste."
return 'janitor'
elif "back" in next:
return 'front_corridor'
else:
print "Do WHAT with WHAT?"
return 'janitor'
def keypad(self):
print "Above the keypad there is a sign that reads:\n-----------\nInput a 3 digit code.\nWarning: If code is incorrect 3 times, keypad will self-destruct.\n-----------"
code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
guess = raw_input("Password: ")
guesses = 0
while guess != code and guesses < 2:
print "BZZZZZEDD!"
guesses += 1
guess = raw_input("Password: ")
if guess == code:
print "The keypad beeps in acceptance. Wow, that was a good guess"
print "The door swings open."
print "Behind the door is a long bridge suspended over a lake of lava."
return 'bridge'
elif "key" in guess and key == True:
print "You flash your card key across the keypad."
print "There is a beep as the door swings open."
print "Behind the door is a long bridge suspended over a lake of lava."
return 'bridge'
else:
print "The keypad buzzes one last time and then you hear a sickening melting"
print "sound as the lock mechanism fuses together."
print "There is a small clicking while the keypad countsdown."
print "3"
time.sleep(1)
print "2"
time.sleep(1)
print "1"
time.sleep(1)
print "There is a large explosion and you are caught right in the middle of it."
print "The fiery blast tears your skin from your body as you scream in agony."
return 'death'
def bridge(self):
print "You carefully walk onto the bridge."
print "One false move and you could be dead."
print "Across the bridge is a door leading to the outside world."
next = raw_input(prompt)
if "jump" in next:
print "You jump to your death."
print "Probably not the best idea."
elif "run" in next:
print "You run"
a_game = Game("intro")
a_game.play()
Your approach seems to work fine, but you have a couple of bugs. In cell(), you need a : after the elif "febreeze"... statement (before the comment starts). Also, at the end of that elif block, you need to return 'cell'. With these changes, I can pick up the Febreeze and use it.
If you define the inventory as a list(that's what I did), then you can do:
class Attributes:
def __init__(self, inventory):
self.inventory = inventory
Player = Attributes([])
Player.inventory.append("Febreeze")
The square brackets make the inventory, and the "append" adds Febreeze to it.
if you tryed to define it as a list e.g (guessing this is on python)
def inventory[]
inventory.append
add item (inventory)
cannot rember how to add it to the inventory but there is the basics