resetting raw_input within a while loop (python) - python

So I'm trying to get this engine to work, and I did, but it's broken my program. (from LPTHW)
I am basically trying to access a function where it gets an input from the user 11 times, if the user fails to guess the correct input, they die (in game) but my fix for sending the prompts from the engine to the functions, seemed to break the function where I get an input 11 times and just uses the same guess for all 11 inputs.
Here is the main engine
globvar = ' '
class Game(object):
def __init__(self, start):
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."
]
self.start = start
def play(self):
# next_room_name is taken from init argument start
next_room_name = self.start
while True:
global globvar
print "\n--------"
# set variable room to get function from next_room_name
room = getattr(self, next_room_name)
print room.__doc__
if room == self.laser_weapon_armory:
prompt = raw_input("[keypad]> ")
elif room == self.escape_pod:
prompt = raw_input("[pod #]> ")
else:
prompt = raw_input("> ")
globvar = prompt
# unpacks function from next_room_name into room
next_room_name = room()
And here is the function im trying to get to work
def laser_weapon_armory(self):
"""
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
while guess != code and guesses < 10:
print "BZZZZEDDD!"
guesses += 1
guess = globvar
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'
And here is the output I get
--------
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.
[keypad]> 124
BZZZZEDDD!
BZZZZEDDD!
BZZZZEDDD!
BZZZZEDDD!
BZZZZEDDD!
BZZZZEDDD!
BZZZZEDDD!
BZZZZEDDD!
BZZZZEDDD!
BZZZZEDDD!
The lock buzzes one last time and then you hear a sickening
melting sound as the mechanism is fused together.
You decide to sit there, and finally the Gothons blow up the
ship from their ship and you die.

is this the kinda thing you're looking for? your question doesn't seem to be very clear
while guess != code and guesses < 10:
guess = raw_input("BZZZZEDDD! - try again?")
guesses += 1
guess = ''

Related

Python (linux) Text based game input error

I have been working on a text-based adventure game. I've revised it a few times and can't seem to get the outcome I want, when I attempt to create EVENTS rather than simply relying on an abundance of PRINT strings. Whenever I choose the option I want (door 1 in this case), then the following options, the input is unresponsive or gives me an error. Below is a portion of the code for door 1. A little clarity would be appreciated!
def main():
import sys
from colorama import init
init()
init(autoreset=True)
from colorama import Fore, Back, Style
def run_event(event):
text, choices = event
text_lines = text.split("\n")
for line in text_lines:
print(Style.BRIGHT + line)
print()
choices = choices.strip()
choices_lines = choices.split("\n")
for num, line in enumerate(choices_lines):
print(Fore.GREEN + Style.BRIGHT + str(num + 1) + ". " + line)
print()
return colored_input()
def colored_input():
return input(Fore.YELLOW + Style.BRIGHT + "> ")
print ("")
print ("")
print (" WELCOME TO THE MAZE ")
print ("")
print ("")
print ("You have found yourself stuck within a dark room, inside this room are 5 doors.. Your only way out..")
print ("")
print ("Do you want to enter door 1,2,3,4, or 5?")
print ("")
EVENT_DOOR1 = ("""
Theres an alien eating what appears to be a human arm, though its so damaged it's hard to be sure. There is a knife next to the alien.
what do you want to do?
""","""
Go for the knife
Attack alien before it notices you
""")
EVENT_ALIEN = ("""
You approach the knife slowly, While the alien is distracted. You finally reach the knife, but as you look up, the alien stares back at you.
You make a move to stab the alien, but he is too quick. With one swift motion, the alien thrusts you into the air.
You land hard, as the alien makes it's way towards you again. What should you do?
""", """
Accept defeat?
Last ditch effort?
""")
EVENT_ALIEN2 = ("""
You catch the alien off-guard. He stumbled and hisses in your direction. You scream in terror before he grabs the knife, and punctures your throat as he rips off your limbs.")
You died.. GAME OVER.. Mistakes can't be made this soon.. OUCH
""")
door = colored_input()
if door == "1":
run_event(EVENT_DOOR1)
alien = colored_input()
if alien == "1":
run_event(EVENT_ALIEN)
elif alien == "2":
run_event(EVENT_ALIEN2)
restart=input("Start over? Yes or No? ").lower()
if restart == "yes":
sys.stderr.write("\x1b[2J\x1b[H")
main()
else:
exit()
main()
You run_event function unnecessarily makes another call to colored_input() when it returns, causing the unresponsiveness as the script waits for another input. Remove the return colored_input() line and your code would work.
Also note that you should add a comma to the single-item tuple assigned to EVENT_ALIEN2; otherwise it would be evaluated as a string:
EVENT_ALIEN2 = ("""
You catch the alien off-guard. He stumbled and hisses in your direction. You scream in terror before he grabs the knife, and punctures your throat as he rips off your limbs.")
You died.. GAME OVER.. Mistakes can't be made this soon.. OUCH
""",)

python global name not defined after transition to classes

I've found a few versions of this question on the site, but none of the answers quite give me an answer I understand (this question is the closest, but the 'already answered' answer seemed to go off in a different direction).
I'm working my way through the learn python the hard way book and have gotten to the point where I'm trying to build a simple combat system for a game. The good news is that it seems to work when I leave it as a stand alone program. The bad news is that it breaks as soon as I try and add it as a class. I can add the full code if it is helpful, but I think the question is essentially related to code that looks like this:
class Room1(Scene):
def kick():
#things happen here
def start():
move = raw_input("> ")
if move == "kick":
kick()
start()
This worked fine when it was just a standalone set of defs, but now that I've added classes it throws up a global name error when move == kick. What am I missing?
Thanks in advance, sorry if there is an obvious answer that I'm missing.
Thanks to everyone for the quick responses! It looks like it may be helpful for me to add the entire code. Just to be clear, this is part of a larger game modeled on example 43 from Learn Python the Hard Way. I very much appreciate the suggestions on improving the structure, but my sense right now is that I want to figure out why this doesn't work with the structure I almost understand before moving on to change more things. Of course, I'm more than willing to accept an answer of "what you are trying to do does not fit in the structure you are trying to use."
When I run the code below as part of a larger structure (in the interest of space I won't paste the entire thing, but the game engine structure is linked to above) I get the error I described. I tried adding 'self.start()' or 'Room1.start()' I get errors that name 'self' or name 'Room1' is not defined.
class Room1(Scene):
gothon_power = 500
move_points = 10
damage = 0
def kick(self):
global gothon_power
global move_points
global damage
damage = randint(10,201)
gothon_power = gothon_power - damage
move_points = move_points - 2
result()
def punch(self):
global gothon_power
global move_points
global damage
damage = randint(1, 101)
gothon_power = gothon_power - damage
move_points = move_points -1
result()
def result(self):
if gothon_power > 0 and move_points > 1:
print "You did %s damage." % damage
print "The Gothon is down to %s health points." % gothon_power
print "You are down to %s move points." % move_points
print "\n"
print "What's your next move?"
move = raw_input("> ")
if move == "kick":
kick()
elif move == "punch":
punch()
else:
print "This isn't going to go anywhere unless you type 'kick' or 'punch'"
print "\n"
result()
elif gothon_power > 0 and move_points == 1:
print "You did %s damage." % damage
print "The Gothon is down to %s health points." % gothon_power
print "You are down to %s move points." % move_points
print "\n"
print "What's your next move? Remember, you only have 1 move point."
move = raw_input("> ")
if move == "kick":
print "You don't have enough move points for a kick."
print "\n"
result()
elif move == "punch":
punch()
else:
print "This isn't going to go anywhere unless you type 'kick' or 'punch'"
print "\n"
result()
elif gothon_power < 1 and move_points > 0:
print "Congratuations, you killed the Gothon!"
return 'room2'
else:
print "The Gothon still has health but you don't have moves."
print "You know what that means."
print "\n"
print "The Gothon killed you."
return 'death'
def start(self):
print "It is time to fight the Gothon"
print "First, let's pause to explain the fighting rules."
print "\n"
print "The Gothon has 500 health points."
print "You have 10 move points."
print "\n"
print "Kicks cost 2 move points and do between 10 and 200 points of damage."
print "Punches cost 1 move opint and do between 1 and 100 points of damage."
print "\n"
print "If you get rid of all 500 Gothon health points before you run out of"
print "move points you win. If you run out of move points before the Gothon"
print "moves out of health points you lose."
print "\n"
print "What's your first move?"
move = raw_input("> ")
if move == "kick":
kick()
elif move == "punch":
punch()
else:
print "This isn't going to go anywhere unless you type 'kick' or 'punch'"
start()
start()
A proper set of methods on a class will look like:
class Room1(Scene):
def kick(self):
#things happen here
def start(self):
move = raw_input("> ")
if move == "kick":
self.kick()
Room1().start()
But you might want to rethink your design a little bit. It really doesn't make sense for a Scene to query for input. You'll have to replicate that code in every room in your game.
Think about this kind of top-level driver for a minute:
game = Game()
starting_room = FrontPorch()
game.move_to(starting_room)
while not game.is_over():
move = raw_input("> ")
cmd, args = move.split(None, 1)
game.current_room.do_command(cmd, args)
Then let each room process the commands that it does specially. At the base level Room class, you can implement commands that are common to most rooms, like "GOTO", "LOOK", "WHERE", etc. Then rooms that allow kicking would override do_command and include logic like you have now.
Here is a presentation I gave at PyCon '06 on writing a text adventure. Skip over the parsing stuff, and go to the part where the game/room/items design is described. You don't have to follow this design verbatim, but you might get some ideas about how your objects and classes will interact. Think about that before actually diving in to write a lot of code.
You can't execute instance methods of a class, without creating an instance. For example, you could instead write:
class Room1(Scene):
def kick(self):
#things happen here
def start(self):
move = raw_input("> ")
if move == "kick":
self.kick()
room = Room1()
room.start()
However, I don't recommend using a class at all in this case. Classes are meant to give a way to represent your own custom objects with state. For example, you could have a Monster class with attributes damage, name, etc.
For this example that you show, it's probably better to just use a function for Room1.
To call kick() as a method you need to use the self.<method Name> syntax and add self as the first argument to it:
def kick(self):
#things happen here
print('kicking')
#call method
self.kick()
or additionally make kick() a static method by calling simply
A.kick()

Python pass on from a class

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.

NameError: name 'Game' is not defined, but it is

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):).

Learn Python the Hard Way ex41 Extra Credit

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.

Categories

Resources