I'm trying to pass on the value of elf_rescued from the class InterrogationRoom to the class Armory. If the elf is rescued then I would like the user to be able to open the weapon locker, however if he isn't then the locker should remain untouched (as he won't tell you about your gear then). I get more confused with each attempt. Can anyone give me a hint on what I'm doing wrong, please?
The error I am getting with this method is:
You enter the armory, where you see a weapons locker and 3 orcs in the back of the room.
What do you do?
open locker
Traceback (most recent call last):
File "C:/Dropbox/Dropbox/Python/Python2/You make a game/start.py", line 231, in
a_game.play()
File "C:/Dropbox/Dropbox/Python/Python2/You make a game/start.py", line 47, in play
next_scene_name = current_scene.enter()
File "C:/Dropbox/Dropbox/Python/Python2/You make a game/start.py", line 189, in enter
elif "open locker" in action and elf_rescued:
NameError: global name 'elf_rescued' is not defined
from sys import exit
from random import randint, randrange
class Scene(object):
def enter(self):
print "This scene is not yet configured. Subclass it and implement enter()."
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
while True:
print "\n-------------------------------------------------------------------------------------------------"
next_scene_name = current_scene.enter()
current_scene = self.scene_map.next_scene(next_scene_name)
class Death(Scene):
deaths = [
"You have died. GAME OVER."
"You failed. Restart the script to try again."
]
def enter(self):
print Death.deaths[randint(0, len(self.deaths)-1)]
exit(1)
class Prison(Scene):
def enter(self):
print "Wandering the Groovy Basin Woods with your elven comrade you were attacked by a pack of Orcs."
print "Their Shaman cast a spell on you which made you unconcious."
print "You wake up and find yourself in a prison cell, with no sign of your partner."
print "One of the guards is sitting at a table at the end of the room."
print "The green beast is half-drunk, half-sleeping."
print "What do you do?"
got_bone = False
while True:
action = raw_input("> ")
if action == "search cell" and not got_bone:
print "You start searching your cell and find a sharp object that must have " \
"been someone's 'Fibula'(the smaller of the two leg bones located below the knee cap) a while ago."
print "You pick it up."
got_bone = True
elif action == "call guard" and not got_bone:
print "You whistle the guard(who doesn't like your attitude and hates your race in general), " \
"he jumps up, opens your cell and starts beating you. Once he amused himself enough, he closes " \
"your cell and goes back to his chair."
elif action == "call guard" and got_bone:
print "The guard comes and opens your cell, hoping he can beat the living soul out of you."
print "Your true warrior instinct does it's job and makes you stab the bone in his throat."
print "You leave the cell and go on to the next room."
return 'inter_room'
elif action == 'open cell' and got_bone:
print "You attempt to open the cell with your extra Figula, and succeed."
print "Luckily the prison is dark enough and the orc is drunk enough for you to leave the room " \
"unnoticed."
return 'inter_room'
else:
print "You can't do that."
return 'prison_cell'
class InterrogationRoom(Scene):
def enter(self):
print "Coming out of the prison area you find yourself on a long, narrow corridor with doors on each side."
print "Passing one of the doors you see your comrade tied up to a strappado."
print "He is clearly in a lot of pain and by the looks of his body this isn't the first torture device " \
"he was experimented with."
print "Taking him with you could be risky as he isn't in the shape to move on his own."
print "However, he is your comrade ever since you fought together in the 'War of the Seven Armies'."
print "Will you ease his pain and make sure he won't be tortured by the orcs anymore or will you take him " \
"with you?"
def situation_change():
return elf_rescued
action = raw_input("> ")
if "leave him" in action:
print "As hard it is, you decide to leave him behind. You grab a dagger from the table and " \
"push it right in his chest. You leave the room."
return 'armory'
elif "rescue him" in action:
print "You cut him down from the rope. He tells you that all your gear has been taken to the Armory. " \
"However, one of the guards has the key to open the weapon locker."
print "You decide to go to the Guards' Quarters."
elf_rescued = True
situation_change()
return 'guards_quarters'
else:
print "You can't do that."
return 'inter_room'
class GuardsQuarters(Scene):
def enter(self):
print "You find yourself at the entrance of the Guards' Quarters."
print "There are at least two dozen drunk orcs in this place. Some playing cards and some doing, whatever" \
"drunk orcs do in a barack at night time."
print "You see a key chain hanged on a nail at the other end of the room. There are some barrels around it."
print "How do you approach it?"
action = raw_input("> ")
if "sneak over" in action:
print "You start sneaking "
elif "hide behind barrel" in action:
print "You hide behind one of the barrels. Lucky for you a guard was just passing by and didn't" \
"notice you."
print "You grab the key and sneak out the room."
return 'armory'
else:
print "You can't do that."
return 'guards_quarters'
class Armory(Scene):
def override(self):
super(InterrogationRoom).situation_change()
def enter(self):
print "You enter the armory, where you see a weapons locker and 3 orcs in the back of the room."
print "What do you do?"
action = raw_input("> ")
while True:
if "attack" in action and not elf_rescued:
print "You can't attack them without a weapon."
return 'armory'
elif "leave" in action:
print "You leave and keep going ahead on the main corridor."
return 'main_hall'
elif "open locker" in action and elf_rescued:
print "You open the weapons locker, where you get a nice weapon and shield."
locker_opened = True
elif "attack" in action and locker_opened:
print "You attack the orc pack from behind. Cutting down two heads right away."
print "The third one jumps away and looks angry as hell."
print "Prepare for battle."
else:
print "You can't do that."
return 'armory'
class Map(object):
scenes = {
'prison_cell': Prison(),
'inter_room': InterrogationRoom(),
'guards_quarters': GuardsQuarters(),
'armory': Armory(),
'main_hall': BarackMainHall(),
'death': Death()
}
def __init__(self, start_scene):
self.start_scene = start_scene
def next_scene(self, scene_name):
return Map.scenes.get(scene_name)
def opening_scene(self):
return self.next_scene(self.start_scene)
a_map = Map('prison_cell')
a_game = Engine(a_map)
a_game.play()
Before all classes, define elf_rescued as a global variable:
elf_rescued= False
Then, in each method you use elf_rescued declare
global elf_rescued
before making any use of it, especially assignment.
I don't understand what you want to do with method situation_change. You probably just need to set elf_rescued= True and get rid of this method.
Related
My problem actually occurs in LockedRoom():
The error python throws is:
Traceback (most recent call last):
File "C:\Users\Tank\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Enthought\CastleGame1.py", line 479, in <module>
a_game.play()
File "C:\Users\Tank\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Enthought\CastleGame1.py", line 33, in play
next_scene_name = current_scene.enter()
File "C:\Users\Tank\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Enthought\CastleGame1.py", line 147, in enter
has_key = "key" in Person.items
AttributeError: class Person has no attribute 'items'
So, I believe the problem is to do with checking for, or putting "Key" in the
person's items. I then want to check this list to see if the warrior is carrying it. If he is, then he should be able to open the door. If not, then the door should remain closed. I need to repeat this again at the end for TowerRoom. In that case, I need to check for up to 3 different items. I have attached the code. Hopefully, the error is a very simple one.
from sys import exit
from random import randint
key = False
brick = False
candle = False
Cup = False
class Scene(object):
def enter(self):
print "This scene is not yet configured."
exit(1)
class Person:
def __init__(self, name):
self.name = name
self.items = []
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
last_scene = self.scene_map.next_scene('finished')
while current_scene != last_scene:
next_scene_name = current_scene.enter()
current_scene = self.scene_map.next_scene(next_scene_name)
current_scene.enter()
class Death(Scene):
quips =[
"You really suck at this.",
"Why don't you try a little harder next time.",
"Well... that was a very stupid thing to do.",
"I have a small puppy that's better at this than you.",
"why don't you just give up now.",
"Please, stop killing me!",
"Your mom would be proud of you... if she were smarter."
]
def enter(self):
print Death.quips[randint(0, len(self.quips)-1)]
exit(0)
class MainGate(Scene):
def enter(self):
print "Welcome to Luke's first Text based game."
print "It currently has no name, nor will it ever have one."
print "Because it kind of sucks a little bit."
print"----------------------------------------"
print "Evil Dr. Onion has stollen the Mushroom Kingdoms princess"
print "You have chased him down for months through rain, snow"
print "and desserts. You have finally tracked him down."
print "In front of you is a huge castle. You go through the giant"
print "entrance to begin your search for the princess. Nobody"
print "know what may await you ahead."
print "Do you want to enter the Castle?"
print "1. Yes"
print "2. No"
action = raw_input(">")
if action == '1':
return 'central_corridor'
elif action == '2':
print "What? You are leaving and giving up on the princess"
print "already? God will certainly smite you for this!!!"
return 'death'
else:
print "Please choose an action numerically using the numpad"
print "on your computer."
return 'MainGate'
class CentralCorridor(Scene):
def enter(self):
print "You enter the castle. In fron of you stands a giant onion"
print "monster. It looks at you with its big, bulging eye. Your"
print "own eyes begin to weep as you look at this... thing."
print "The giant onion monster begins to charge at you, waving its"
print "sword over what I suppose would be its head."
print "what do you do?"
print "1. Try and fight the giant onion with your sword."
print "2. Try and dodge out of the way of the onion and run past it."
print "3. Throw something at the onion."
print "4. Stand there and scream at the onion."
action = raw_input(">")
if action == '1':
print "You take your sword out of its sheath. Waiting for the onion"
print "to reach you so that you can stab it in its giant eye."
print "however as it gets closer its stench gets worse and worse."
print "It gets so bad that you can hardly see!"
print "You try and swing at the onion, and miss!"
print "You feel a stabbing pain in your right shoulder"
print "and then everything goes black."
return 'death'
elif action == '2':
print "As the onion charges you, you jump out of the way."
print "However, the giant onion is much quicker than you expected."
print "You look down to see a sword protruding from your stomach."
print "You scream in pain and die."
return 'death'
elif action == '3':
print "You look in your pockets to find something to throw at"
print "the onion."
print "You find a rubber duck and throw it at the onion. Unfortunately, it"
print "does nothing but distracts the onion from you for a few"
print "short seconds. After it focuses its attention back on you,"
print "it eats your face off."
return 'death'
elif action == '4':
print "You choose to stand and scream at the onion at the highest"
print "pitch your girly little voice will allow."
print "The onion, hearing your scream, is terrified. It turns"
print "around and rolls away as quickly as its little legs and can"
print "carry it. You quickly catch up with it and cut its little"
print "legs right off, before hurrying to the next room."
return 'locked_room'
else:
print "please choose an appropriate action dear sir. Otherwise,"
print "you will never be able to rescue the princess."
return 'central_corridor'
class LockedRoom(Scene):
def enter(self):
print "You are standing in a room with just a door in front of you."
print "What do you do?"
print "1. Try and open the door."
has_key = "key" in Person.items
if not has_key: print "2. pick up the key"
action = raw_input(">")
if (action == '1' and has_key):
print "You unlock and open the door."
return 'monty_hall_room'
elif (action == '1' and not has_key):
print "the door will not budge"
return 'locked_room'
elif (action == '2' and not has_key):
print "you picked up the key."
Person.items.append("key")
return 'locked_room'
else:
print "Please enter a numeric value as something to do."
print "Otherwise we might be here all day."
return 'locked_room'
class Finished(Scene):
def enter(self):
print "You won! Good job."
return 'finished'
class Map(object):
scenes = {
'main_gate': MainGate(),
'central_corridor': CentralCorridor(),
'locked_room': LockedRoom(),
'monty_hall_room': MontyHallRoom(),
'pickel_room': PickleRoom(),
'death': Death(),
'finished': Finished(),
}
def __init__(self, start_scene):
self.start_scene = start_scene
def next_scene(self, scene_name):
val = Map.scenes.get(scene_name)
return val
def opening_scene(self):
return self.next_scene(self.start_scene)
warrior = Person("Soldat")
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()
I just need a way to use a class 'list' and put things in and out of it in the other classes. Then, use whatever is contained in that list to open a door or slay a monster.
Any help anyone could provide would be greatly appreciatd.
You need create a "person" instance (you already did this), instead of using the class:
warrior = Person.new("penne12")
Or use the one you created
Then you can use your "warrior":
warrior.name #=> "penne12"
warrior.items #=> []
This is because the class itself doesn't store the name or items, the instance of the class (created when you do Person.new) contains the item array and the name. Trying to get the attributes of the class won't work.
Further reading
I'm working through Learn Python the Hard Way by Zed Shaw and am at exercise 43.
The exercise is a script for a game that uses objects and classes. I've copied Zeds script and just want to get it to run.
I'm hoping that if I can see it running I can work back and see how it operates.
OK, so the error returned in the terminal is:
Traceback (most recent call last):
File "ex43.py", line 206, in <module>
a_game.play()
File "ex43.py", line 20, in play
next_scene_name = current_scene.enter()
AttributeError: 'NoneType' object has no attribute 'enter'
The current scene is central_corridor which is called at the end of the script (meant to start the game). Map has a dict where central_corridor: Central_Corridor().
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()
But when I look at the code block for CentralCorridor() there is indeed an enter attribute (a function).
class CentralCorridor(Scene):
def enter(self):
print "bla bla bla..."
It's probably apparent to experienced OOP programmers that I'm finding this tricky (Thankfully for my confidence, the internet says many folk have a hard time understanding OOP at first).
Here is the script in full. How do I get it to run? Is my line of thinking and "flow" above way off or on track?
from sys import exit
from random import randint
class Scene(object):
def enter(self):
print "This scene is not yet configured. Subclass it and implement enter()."
class Engine(object):
def __init__(self, scene_map):
print "Engine __init__ has scene_map", scene_map
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
print "Play's first scene", current_scene
while True:
print "\n--------"
next_scene_name = current_scene.enter()
print "next scene", next_scene_name
current_scene = self.scene_map.next_scene(next_scene_name)
print "map returns new scene", current_scene
class Death(Scene):
quips = [
"You died. You kinda suck at this.",
"Your mom would be proud... if she were smarter",
"Such a luser",
"I have a small puppy that's better at this."
]
def enter(self):
print Death.quips[randint(0, len(self.quips)-1)]
exit(1)
class CentralCorridor(Scene):
def enter(self):
print "The Gothons of Planet Percal #25 have invaded your ship and destroyed"
print "your entire crew. You are the last surviving member and your last"
print "mission is to get the neutron destruct bomb from the Weapons Armory,"
print "put it in the bridge, and blow the ship up after getting into an "
print "escape pod."
print "\n"
print "You're running down the central corridor to the Weapons Armory when"
print "a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume"
print "flowing around his hate filled body. He's blocking the door to the"
print "Armory and about to pull a weapon to blast you."
action = raw_input("> ")
if action == "shoot!":
print "Quick on the draw you yank out your blaster and fire it at the Gothon."
print "His clown costume is flowing and moving around his body, which throws"
print "off your aim. Your laser hits his costume but misses him entirely. This"
print "completely ruins his brand new costume his mother bought him, which"
print "makes him fly into an insane rage and blast you repeatedly in the face until"
print "you are dead. Then he eats you."
return 'death'
elif action == "dodge!":
print "Like a world class boxer you dodge, weave, slip and slide right"
print "as the Gothon's blaster cranks a laser past your head."
print "In the middle of your artful dodge your foot slips and you"
print "bang your head on the metal wall and pass out."
print "You wake up shortly after only to die as the Gothon stomps on"
print "your head and eats you."
return 'death'
elif action == "tell a joke":
print "Lucky for you they made you learn Gothon insults in the academy."
print "You tell the one Gothon joke you know:"
print "Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr."
print "The Gothon stops, tries not to laugh, then busts out laughing and can't move."
print "While he's laughing you run up and shoot him square in the head"
print "putting him down, then jump through the Weapon Armory door."
return 'laser_weapon_armory'
else:
print "DOES NOT COMPUTE!"
return 'central_corridor'
class LaserWeaponArmory(Scene):
def enter(self):
print "You do a dive roll into the Weapon Armory, crouch and scan the room"
print "for more Gothons that might be hiding. It's dead quiet, too quiet."
print "You stand up and run to the far side of the room and find the"
print "neutron bomb in its container. There's a keypad lock on the box"
print "and you need the code to get the bomb out. If you get the code"
print "wrong 10 times then the lock closes forever and you can't"
print "get the bomb. The code is 3 digits."
code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
guess = raw_input("[keypad]> ")
guesses = 0
while guess != code and guesses < 10:
print "BZZZZEDDD!"
guesses += 1
guess = raw_input("[keypad]> ")
if guess == code:
print "The container clicks open and the seal breaks, letting gas out."
print "You grab the neutron bomb and run as fast as you can to the"
print "bridge where you must place it in the right spot."
return 'the_bridge'
else:
print "The lock buzzes one last time and then you hear a sickening"
print "melting sound as the mechanism is fused together."
print "You decide to sit there, and finally the Gothons blow up the"
print "ship from their ship and you die."
return 'death'
class TheBridge(Scene):
def enter(self):
print "You burst onto the Bridge with the netron destruct bomb"
print "under your arm and surprise 5 Gothons who are trying to"
print "take control of the ship. Each of them has an even uglier"
print "clown costume than the last. They haven't pulled their"
print "weapons out yet, as they see the active bomb under your"
print "arm and don't want to set it off."
action = raw_input("> ")
if action == "throw the bomb":
print "In a panic you throw the bomb at the group of Gothons"
print "and make a leap for the door. Right as you drop it a"
print "Gothon shoots you right in the back killing you."
print "As you die you see another Gothon frantically try to disarm"
print "the bomb. You die knowing they will probably blow up when"
print "it goes off."
return 'death'
elif action == "slowly place the bomb":
print "You point your blaster at the bomb under your arm"
print "and the Gothons put their hands up and start to sweat."
print "You inch backward to the door, open it, and then carefully"
print "place the bomb on the floor, pointing your blaster at it."
print "You then jump back through the door, punch the close button"
print "and blast the lock so the Gothons can't get out."
print "Now that the bomb is placed you run to the escape pod to"
print "get off this tin can."
return 'escape_pod'
else:
print "DOES NOT COMPUTE!"
return "the_bridge"
class EscapePod(Scene):
def enter(self):
print "You rush through the ship desperately trying to make it to"
print "the escape pod before the whole ship explodes. It seems like"
print "hardly any Gothons are on the ship, so your run is clear of"
print "interference. You get to the chamber with the escape pods, and"
print "now need to pick one to take. Some of them could be damaged"
print "but you don't have time to look. There's 5 pods, which one"
print "do you take?"
good_pod = randint(1,5)
guess = raw_input("[pod #]> ")
if int(guess) != good_pod:
print "You jump into pod %s and hit the eject button." % guess
print "The pod escapes out into the void of space, then"
print "implodes as the hull ruptures, crushing your body"
print "into jam jelly."
return 'death'
else:
print "You jump into pod %s and hit the eject button." % guess
print "The pod easily slides out into space heading to"
print "the planet below. As it flies to the planet, you look"
print "back and see your ship implode then explode like a"
print "bright star, taking out the Gothon ship at the same"
print "time. You won!"
return 'finished'
class Map(object):
scenes = {
'central_corridor': CentralCorridor(),
'laser_weapon_armory': LaserWeaponArmory(),
'the_bridge': TheBridge(),
'escape_pod': EscapePod(),
'death': Death()
}
def __init__(self, start_scene):
self.start_scene = start_scene
print "start_scene in __init__", self.start_scene
def next_scene(self, scene_name):
print "start_scene in next_scene"
val = Map.scenes.get(scene_name)
print "next_scene returns", val
def opening_scene(self):
return self.next_scene(self.start_scene)
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()
Hmm, your "next_scene" function in class Map returns nothing.
Add:
return val
to the end of this function.
Simply Solve like:
while True and and current_scene is not None:
print "\n--------"
next_scene_name = current_scene.enter()
current_scene = self.scene_map.next_scene(next_scene_name)
Because 'finished' doesn't exists as a scene in the Map.
Try handle it this way in the while loop in Engine.play()
while True:
print "\n--------"
next_scene_name = current_scene.enter()
if next_scene_name != 'finished':
current_scene = self.scene_map.next_scene(next_scene_name)
else:
print "You finally escaped the Planet Percal #25"
exit(1)
The error is returned when finished is returned by enter function of class EscapePod(Scene): and this key finished is searched the dictionary scenes through code in next_scene function --> Map.scenes.get(scene_name) where scene name is passed as finished.
We can see from scenes dictionary that no value is present for the key finished and hence it throws the error:
File "ex43.py", line 20, in play
next_scene_name = current_scene.enter()
AttributeError: 'NoneType' object has no attribute 'enter'
Properly handle the value finished as in the code below in the next_scene function so that the key is not searched when finished value is passed to the function.
def next_scene(self,scene_name):
if scene_name == 'finished':
print "Game Done"
exit(1)
return Map.scenes.get(scene_name)
I am learning python using the book Learn python the hard way. I am doing one of the exercises, which contains many if loop's. I met an error which says Game is not defined, but I did define it before. Anyone ideas?
from sys import exit
from random import randint
class Game(object):
def __init__(self, start):
self.quips = [
"You died. You kinda suck at this.",
"Nice job, you died ... jackass.",
"Such a luser.",
"I have a small puppy that's better at this."]
slef.start = start
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(quips)-1)]
exit(1)
def central_corridor(self):
print "The Gothons of Planet Percal #25 have invaded your ship and destroyed"
print "your entire crew. You are the last surviving member and your last"
print "mission is to get the neutron destrut bomb from the Weapons Armory,"
print "put it in the bridge, and blow the ship up after getting into an "
print "escapr pod."
print "\n"
print "You're running down the central corridor to the Weapons Armory when"
print "a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume"
print "flowing around his hate filled body. He's blocking the door to thr"
print "Armory and about to pull a weapon to blast you."
action =raw_input("> ")
if action == "shoot!":
print "Quick on the draw you yank out your blaster and fire it at the Gothan."
print "His clown costume is flowing and moving around his body, which throws"
print "off your aim. Your laser hits new costume but misses him entirely. This"
print "completely ruins his brand new costumr his mother bought him, which"
print " makes him fly into an insane rage and blast you repeatedly in the face until"
print "you are dead. Then he eats you."
return 'death'
elif action =="dodge!":
print "Like a world class boxer you dodge, weave, slip and slide right"
print "as the Gothon's blaster cranks a laser past your head."
print "In the middle of your artful dodge your foot slips and you"
print "You wake up shortly after only to die as the Gothon stomps on"
print "your head and eats you."
return 'death'
elif action =="tell a joke":
print "Lucky for you they made you learn Fothon insults in the acsdemy."
print "You tell teh one Gothon k=joke you know:"
print "Lbhe zbgure vf fb sng, jura fur fvgf nebhag gur ubhfr, fur fvgf nrbhaq"
print "The Gothon stops, tries not to laugh, then busts out laughing and can't"
print "While he's laughing you run up and shoot him square in the head"
print "putting hm down, then jump through the Weapon Armory door."
return 'laser_weapon_asmory'
else:
print "DOES NOT COMPUTE!"
return 'central_corridor'
def laser_weapon_armory(self):
print " You do a dive roll into the Weapon Armory, crough and scan the room"
print "for more Gothans that might be hiding. It's dead quiet, too quiet."
print "You stand up and run to the far side of the room and find the"
print "neutron bomb in its container. There's a keypad lock on the code"
print "and you need the code to get the bomb out. If you get the code"
print "wrong 10 times then the lock closes forever and you can't"
print "get the bomb. The code is 3 digits."
code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
guess = raw_input("[keypad]> ")
guesses = 0
while guess != code and guesses < 10:
print "BZZZZEDDD!"
guesses += 1
guess = raw_input("[keypad]> ")
if guess == code:
print "The container clicks open and the seal breaks, letting gas out."
print "You grab the neutron bomb and run as fast as you can to the"
print "bridge where you must place it in the right spot."
return 'the_bridge'
else:
print "The lock buzzes one last time and then you hear s sickening"
print "melting sound as teh mechanism is fused together."
print "You decide to sit there, and finally the Gothons blow up the"
return 'death'
def the_bridge(self):
print "You burst onto the Brisge with the netron destruct bomb"
print "under your arm and surprise 5 Gothon who are trying to"
print "take control of the ship. Each of them has an even uglier"
print "clown costume than the last. They haven't pulled their"
print "weapons out yet, as they see the active bomb under your"
print "arm and don't want to see it off."
action = raw_input("> ")
if action == "throw the bomb":
print "In a panic you throw the bomb at the group of Gothons"
print "and make a leap for the door. Right as you drop it a"
print "Gothon shoots you right in the back kiling you."
print "As you die you see another Gothon frantically try to disarm"
print "the bomb. You die knowing they will probably blow up when"
print "it goes off."
return 'death'
elif action == "slowly place the bomb":
print "You point your blaster at teh bomb under your arm"
print "and the Gothons put their hand up and start to sweat."
print "You inch backwark to the door, open it, and then carefully"
print "place the bomb on the floor, pointing your blaster at it."
print "You then jump back through the door, punch the close button"
print "and blast the lock so the Gothons can't get out."
print "Now that the bomb is placed you run to the escape pod to"
print "get off this tin can."
return 'escapr_pod'
else:
print "DOES NOT COMPUTE!"
return "the_brigde"
def escape_pad(self):
print "You rush through the ship desperately trying to make it to"
print "the escape pod before the whole ship explodes. It seemd like"
print "hardly any Gothons are on the ship, so your run is clear of"
print "interference. YOu get to the chamber with the excape pod, and"
print "now need to pick one to take. Some of them could be damaged"
print "but you don't have time to look. There's 5 pots, which one"
print "do you take?"
good_pod = randint(1,5)
guess = raw_input("[pod #]> ")
if int(guess) != good_pod:
print "You jump into pod %s and hit the eject button." % guess
print "The pod escaped out into the void of space, then"
print "implodes as the hull ruptures, crushing your body"
print "into jam jelly."
else:
print "You jump into pod %s and hit the eject button." % guess
print "The pod eadily slides out into space heading to"
print "the planet below. As it flies to the planet, you look"
print "back and see your ship implode then explode like a"
print "bright star, taking out the Gothon ship at the same"
print "time. You won!"
exit(0)
a_game = Game("central_corridor")
a_game.play()
I think this is the result of an indentation error. In your posted code, you have
class Game(object):
def __init__(self, start):
[...]
print "time. You won!"
exit(0)
a_game = Game("central_corridor")
a_game.play()
So that you're defining a_game inside the Game class, when Game isn't defined yet. Shift it to the left to move it outside the Game scope, i.e.
a_game = Game("central_corridor")
a_game.play()
(on the same level as class Game(object):).
working my way through LPTHW and am stuck on the extra credit for exercise 41:
Extra Credit:
Add cheat codes to the game so you can get past the more difficult
rooms.
Instead of having each function print itself, learn about “doc
string” style comments. Write the room description as doc comments,
and change the runner to print them.
Once you have doc comments as the room description, do you need to
have the function prompt even? Have the runner prompt the user, and
pass that in to each function. Your functions should just be
if-statements printing the result and returning the next room.
As I understand so far using docstrings like this is frowned upon, but here's what I've come up with:
from sys import exit
from random import randint
globvar = ''
def death():
quips = ["You died. You kinda suck at this.",
"Nice job, you died ...jackass.",
"Such a loser.",
"I have a small puppy that's better at this."]
print quips[randint(0, len(quips)-1)]
exit(1)
def central_corridor():
"""The Gothons of Planet Percal #25 have invaded your ship and destroyed
your entire crew. You are the last surviving member and your last
mission is to get the neutron destruct bomb from the Weapons Armory,
put it in the bridge, and blow the ship up after getting into an
escape pod.
You're running down the central corridor to the Weapons Armory when
a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume
flowing around his hate filled body. He's blocking the door to the
Armory and about to pull a weapon to blast you.
"""
action = globvar
if action == "shoot!":
print "Quick on the draw you yank out your blaster and fire it at the Gothon."
print "His clown costume is flowing and moving around his body, which throws"
print "off your aim. Your laser hits his costume but misses him entirely. This"
print "completely ruins his brand new costume his mother bought him, which"
print "makes him fly into an insane rage and blast you repeatedly in the face until"
print "you are dead. Then he eats you."
return 'death'
elif action == "dodge!":
print "Like a world class boxer you dodge, weave, slip and slide right"
print "as the Gothon's blaster cranks a laser past your head."
print "In the middle of your artful dodge your foot slips and you"
print "bang your head on the metal wall and pass out."
print "You wake up shortly after only to die as the Gothon stomps on"
print "your head and eats you."
return 'death'
elif action == "tell a joke":
print "Lucky for you they made you learn Gothon insults in the academy."
print "You tell the one Gothon joke you know:"
print "Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr."
print "The Gothon stops, tries not to laugh, then busts out laughing and can't move."
print "While he's laughing you run up and shoot him square in the head"
print "putting him down, then jump through the Weapon Armory door."
return 'laser_weapon_armory'
else:
print "DOES NOT COMPUTE!"
return 'central_corridor'
def laser_weapon_armory():
"""You do a dive roll into the Weapon Armory, crouch and scan the room
for more Gothons that might be hiding. It's dead quiet, too quiet.
You stand up and run to the far side of the room and find the
neutron bomb in its container. There's a keypad lock on the box
and you need the code to get the bomb out. If you get the code
wrong 10 times then the lock closes forever and you can't
get the bomb. The code is 3 digits.
"""
code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
guess = globvar
guesses = 0
cheat = '007'
while guess != code and guess != cheat and guesses < 10:
print "BZZZZEDDD!"
guesses += 1
guess = raw_input("[keypad]> ")
if guess == code:
print "The container clicks open and the seal breaks, letting gas out."
print "You grab the neutron bomb and run as fast as you can to the"
print "bridge where you must place it in the right spot."
return 'the_bridge'
elif guess == cheat:
print "The container clicks open and the seal breaks, letting gas out."
print "You grab the neutron bomb and run as fast as you can to the"
print "bridge where you must place it in the right spot."
return 'the_bridge'
else:
print "The lock buzzes one last time and then you hear a sickening"
print "melting sound as the mechanism is fused together."
print "You decide to sit there, and finally the Gothons blow up the"
print "ship from their ship and you die."
return 'death'
def the_bridge():
"""You burst onto the Bridge with the netron destruct bomb
under your arm and surprise 5 Gothons who are trying to
take control of the ship. Each of them has an even uglier
clown costume than the last. They haven't pulled their
weapons out yet, as they see the active bomb under your
arm and don't want to set it off.
"""
action = globvar
if action == "throw the bomb":
print "In a panic you throw the bomb at the group of Gothons"
print "and make a leap for the door. Right as you drop it a"
print "Gothon shoots you right in the back killing you."
print "As you die you see another Gothon frantically try to disarm"
print "the bomb. You die knowing they will probably blow up when"
print "it goes off."
return 'death'
elif action == "slowly place the bomb":
print "You point your blaster at the bomb under your arm"
print "and the Gothons put their hands up and start to sweat."
print "You inch backward to the door, open it, and then carefully"
print "place the bomb on the floor, pointing your blaster at it."
print "You then jump back through the door, punch the close button"
print "and blast the lock so the Gothons can't get out."
print "Now that the bomb is placed you run to the escape pod to"
print "get off this tin can."
return 'escape_pod'
else:
print "DOES NOT COMPUTE!"
return "the_bridge"
def escape_pod():
"""You rush through the ship desperately trying to make it to
the escape pod before the whole ship explodes. It seems like
hardly any Gothons are on the ship, so your run is clear of
interference. You get to the chamber with the escape pods, and
now need to pick one to take. Some of them could be damaged
but you don't have time to look. There's 5 pods, which one
do you take?
"""
good_pod = randint(1,5)
guess = globvar
great_pod = 1
if int(guess) == good_pod:
print "You jump into pod %s and hit the eject button." % guess
print "The pod easily slides out into space heading to"
print "the planet below. As it flies to the planet, you look"
print "back and see your ship implode then explode like a"
print "bright star, taking out the Gothon ship at the same"
print "time. You won!"
exit(0)
elif int(guess) == great_pod:
print "You jump into pod %s and hit the eject button." % guess
print "The pod easily slides out into space heading to"
print "the planet below. As it flies to the planet, you look"
print "back and see your ship implode then explode like a"
print "bright star, taking out the Gothon ship at the same"
print "time. You won!"
exit(0)
else:
print "You jump into pod %s and hit the eject button." % guess
print "The pod escapes out into the void of space, then"
print "implodes as the hull ruptures, crushing your body"
print "into jam jelly."
return 'death'
ROOMS = {
'death': death,
'central_corridor': central_corridor,
'laser_weapon_armory': laser_weapon_armory,
'the_bridge': the_bridge,
'escape_pod': escape_pod
}
def runner(themap, start):
next = start
while True:
## Global variable in order to pass prompt value to rooms
global globvar
room = themap[next]
print "\n--------"
print room.__doc__
## Room dependent prompts
if room == laser_weapon_armory:
prompt = raw_input("[keypad]> ")
elif room == escape_pod:
prompt = raw_input("[pod #]> ")
elif room == death:
return 'death'
else:
prompt = raw_input("> ")
## Set raw_input from prompt to Global variable (globvar)
globvar = prompt
next = room()
runner(ROOMS, 'central_corridor')
Everything runs fine except for "return 'death'". It just exits after printing the following:
--------
None
In the runner function near the bottom, I thought adding the 'elif room == death:' bit would work as without it, it just hangs waiting for raw_input() and then prints a random 'quip' as it should after I press ENTER. Can someone help me understand what I'm missing? Any help appreciated!
EDIT
Thanks to some lighting quick feedback this is what I've got, though rocksportrocker's solution is simpler:
def runner(themap, start):
next = start
while True:
## Global variable in order to pass prompt value to rooms
global globvar
room = themap[next]
## Room dependent prompts
if room == laser_weapon_armory:
print "\n--------"
print room.__doc__
prompt = raw_input("[keypad]> ")
elif room == escape_pod:
print "\n--------"
print room.__doc__
prompt = raw_input("[pod #]> ")
elif room == the_bridge:
print "\n--------"
print room.__doc__
prompt = raw_input("> ")
elif room == central_corridor:
print "\n--------"
print room.__doc__
prompt = raw_input("> ")
else:
pass
## Set raw_input from prompt to Global variable (globvar)
globvar = prompt
next = room()
death has no doc string. if room==death then print room.__doc__ prints None. in the following if/elifs you return from the function runnner which results in the programs end.
Your program will work if you add the missing doc string and if you replace return "death" in runner() by a simple "pass", or by ommitting the corresponding elif clause.
So I know this site gets far too many questions about Zed Shaw's Learn Python the Hard Way, but I'm going through ex42., extra credit #3, has got me hung up.
I am having trouble getting the class Engine to effectively start and transition into the class Map where the game can begin going through the different functions that I have defined
the code is as follows:
from sys import exit
from random import randint
class Map(object):
def death():
print quips[randint (0, len(quips)-1)]
exit(1)
def princess_lives_here():
print "You see a beautiful Princess with a shiny crown."
print "She offers you some cake."
eat_it = raw_input(">")
if eat_it == "eat it":
print "You explode like a pinata full of frogs."
print "The Princess cackles and eats the frogs. Yum!"
return 'death'
elif eat_it == "do not eat it":
print "She throws the cake at you and it cuts off your head."
print "The last thing you see is her munching on your face. Yum!"
return 'death'
elif eat_it == "make her eat it":
print "The Princess screams as you cram the cake in her mouth."
print "Then she smiles and cries and thank you for saving her."
print "She points to a tiny door and says, 'The Koi needs cake too.'"
print "She gives you the very last bit of cake and shoves you in."
return 'gold_koi_pond'
else:
print "The Princess looks at you confused and just points at the cake."
return 'princess_lives_here'
class Engine(Map):
def _init_(self, start):
self.quips = [
"You died. You suck at this.",
"Your mom would be proud, if she were smarter",
"Such a luser.",
"I have a small puppy that's better at this."
]
self.start = start
def play(self):
next = self.start
while True:
print "\n-----"
room = getattr(self, next)
next = room()
e = "princess_lives_here".Map.Engine
e.play()
Now the issue is not with the other functions within Map class but making the transition from the class Engine to class Map so the game can continue. It is either not defining 'Map' within the class Engine or in the variable i am setting up at the end and trying to run with the play() command.
Any other links you can point me to in regards to class interaction would be great. thnx again
There's a lot wrong here.
Your code as shown is illegally indented; it looks like __init__() and play() should be indented to be members of class Engine, and death() and princess_lives_here() indented into Map.
The __init__ of a class needs double underscores, not single, on each end.
The line:
e = "princess_lives_here".Map.Engine
is nonsensical python; it starts by trying to find a "Map" attribute in a string. If you want to instance a new object of a class, you'd say
e = Engine( "princess_lives_here" ) # or Map( "...")?
It's unclear to me what you need both Map and Engine for, but I'm guessing you either want Map to be a subclass of Engine (Engine is generic to all games and Map is specific to this game) or you want them to be separate objects, where an Engine and a Map refer back to each other.
As it stands you have Engine as a subclass of Map. If they're supposed to be separate, declare Engine as an object, have its __init__ take both a starting point and a map instance, and do
m = Map()
e = Engine( m, "princess_lives_here" )
from sys import exit
from random import randint
class Map(object):
def __init__(self):
self.quips = [
"You died. You kinda suck at this.",
"Your mom would be proud. If she were smarter.",
"Such a luser.",
"I have a small puppy that's better at this."
]
def death(self):
print self.quips[randint(0, len(self.quips)-1)]
exit(1)
def princess_lives_here(self):
print "You see a beautiful Princess with a shiny crown."
print "She offers you some cake."
eat_it = raw_input("> ")
if eat_it == "eat it":
print "You explode like a pinata full of frogs."
print "The Princess cackles and eats the frogs. Yum!"
return 'death'
elif eat_it == "do not eat it":
print "She throws the cake at you and it cuts off your head."
print "The last thing you see is her munching on your torso. Yum!"
return 'death'
elif eat_it == "make her eat it":
print "The Princess screams as you cram the cake in her mouth."
print "Then she smiles and cries and thanks you for saving her."
print "She points to a tiny door and says, 'The Koi needs cake too.'"
print "She gives you the very last bit of cake and shoves you in."
return 'gold_koi_pond'
else:
print "The princess looks at you confused and just points at the cake."
return 'princess_lives_here'
def gold_koi_pond(self):
print "There is a garden with a koi pond in the center."
print "You walk close and see a massive fin poke out."
print "You peek in and a creepy looking huge Koi stares at you."
print "It opens its mouth waiting for food."
feed_it = raw_input("> ")
if feed_it == "feed it":
print "The Koi jumps up, and rather than eating the cake, eats your arm."
print "You fall in and the Koi shrugs than eats you."
print "You are then pooped out sometime later."
return 'death'
elif feed_it == "do not feed it":
print "The Koi grimaces, then thrashes around for a second."
print "It rushes to the other end of the pond, braces against the wall..."
print "then it *lunges* out of the water, up in the air and over your"
print "entire body, cake and all."
print "You are then pooped out a week later."
return 'death'
elif feed_it == "throw it in":
print "The Koi wiggles, then leaps into the air to eat the cake."
print "You can see it's happy, it then grunts, thrashes..."
print "and finally rolls over and poops a magic diamond into the air"
print "at your feet."
return 'bear_with_sword'
else:
print "The Koi gets annoyed and wiggles a bit."
return 'gold_koi_pond'
def bear_with_sword(self):
print "Puzzled, you are about to pick up the fish poop diamond when"
print "a bear bearing a load bearing sword walks in."
print '"Hey! That\' my diamond! Where\'d you get that!?"'
print "It holds its paw out and looks at you."
give_it = raw_input("> ")
if give_it == "give it":
print "The bear swipes at your hand to grab the diamond and"
print "rips your hand off in the process. It then looks at"
print 'your bloody stump and says, "Oh crap, sorry about that."'
print "It tries to put your hand back on, but you collapse."
print "The last thing you see is the bear shrug and eat you."
return 'death'
elif give_it == "say no":
print "The bear looks shocked. Nobody ever told a bear"
print "with a broadsword 'no'. It asks, "
print '"Is it because it\'s not a katana? I could go get one!"'
print "It then runs off and now you notice a big iron gate."
print '"Where the hell did that come from?" You say.'
return 'big_iron_gate'
def big_iron_gate(self):
print "You walk up to the big iron gate and see there's a handle."
open_it = raw_input("> ")
if open_it == 'open it':
print "You open it and you are free!"
print "There are mountains. And berries! And..."
print "Oh, but then the bear comes with his katana and stabs you."
print '"Who\'s laughing now!? Love this katana."'
return 'death'
else:
print "That doesn't seem sensible. I mean, the door's right there."
return 'big_iron_gate'
class Engine(object):
def __init__(self, o, map):
self.map = map
self.obj = o
def play(self):
nextmap = self.map
while True:
print "\n--------"
room = getattr(self.obj, nextmap)
nextmap = room()
a_map = Map()
a_eng = Engine(a_map, "princess_lives_here")
a_eng.play()