from sys import exit
haskey = 0
# start function
def start():
print "You wake up in an empty room, feels like you've been here for days. You can't remember anything from your past. All there is in the room is a digital clock. It says 3:26am, May 5, 2012. Get out of the room?"
next = raw_input("> ").lower()
if "yes" in next:
lobby()
elif "no" in next:
print "We insist"
else:
print "Try again."
def lobby():
while True:
print "You arrived at a lobby, all you can see are four doors. Which door to enter? (first, second, third, fourth)?"
next = raw_input("> ").lower()
if "first" in next:
firstdoor()
elif "second" in next:
seconddoor()
elif "third" in next:
thirddoor()
elif "fourth" in next:
fourthdoor()
else:
print "Are you dumb and you can't even follow instructions?"
def firstdoor():
print "You arrive at another empty room, examine further or exit?"
choice = raw_input("> ").lower()
if "examine" in choice:
print "A trap door opened, you fell in it and died."
exit()
elif "exit" in choice:
lobby()
else:
print "Are you dumb and you can't even follow instructions?"
def seconddoor():
print "You arrive at the study room, examine room or exit?"
choice = raw_input("> ").lower()
if "examine" in choice:
print "There is a note on the table, read it?"
secondchoice = raw_input("> ").lower()
if "yes" in secondchoice:
note()
elif "no" in secondchoice:
print "Returning to lobby."
lobby()
def note():
print """Security Log (040412): A man from the city travelling along the highway loses control of his vehicle and fell to the cliff. He was able to jump and grab a hold to the bushes growing at the side of the cliff. We were able to rescue him, but as soon as we secured him to the ground he violently reacted to our help and fainted. A few minutes later he was out of control, like he was possessed by a demon. We had no choice but to sedate him and keep him locked in our prison until authorities from the city arrive and examine him. The key to his cell is in the vault in the vault room. The keycode changes depending on the current date.
"""
print "Returning to lobby."
lobby()
def thirddoor():
if haskey == 0:
print "Door is locked, you need a key to continue."
print "%d" % haskey
lobby()
elif haskey == 1:
exit()
def exit():
print "You are now free!"
print "To be continued.."
def fourthdoor():
print "There is a vault inside the room. Use vault?"
usevault = raw_input("> ")
if "yes" in usevault:
vault()
else:
print "Returning to lobby.."
lobby()
def vault():
while True:
print "There is a security code for this door. Enter code:"
code = raw_input("> ")
if "05042012" in code:
print "Correct!"
print "Returning to lobby.."
haskey = int(1)
print "%d" % haskey
lobby()
else:
print "Code Error! Try again?"
start()
I have this mini-text game for a tutorial on python and I'm using the fourthdoor/vault function to ask the player the code and if entered correctly it changes the value of a variable to be used as a key to open the third door. The problem is even if the value of the variable is changed when the vault code is given correctly, I still can't open the door.
Can anyone help me?
When python encounters haskey = int(1) inside of vault, it creates a new local variable called haskey that you can only see inside of vault. You need to tell python that when it sees haskey in that function, you mean the global haskey that you declare at the top of the file. You can do this by adding global haskey to the beginning of vault. ie:
def vault():
global haskey
while True:
print "There is a security code for this door. Enter code:"
code = raw_input("> ")
...
Related
I'm trying to make a simple text adventure game with three choices. But I can't seem to figure out why this isn't working.
This is the code I have been working on:
#Text based medieval adventure game
#Imported libraries are required
import random
import time
def displayWelcome():
print ("\nText adventure game\n")
print ("Welcome to the medieval adventure game!")
print ("You will have many choices through out this game")
print ("Be sure to pick the right one")
print (" Good Luck! ")
answer = askYesNo("Would you like help with this program? (Y/N): ")
if answer == "Y":
helpForUser()
time.sleep(3)
def askYesNo (question):
# This function will ask you a yes or no question and will keep asking until one is chosen.
# The following function is used to erase the variable response of any values
response = None
while response not in ("Y", "N"):
response = input (question).upper()
return response
def helpForUser():
#This function will show the user some helpful advice if they desire it
print ("\n+++++++++++++++++++++++++++++++++++++++ Help +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
print ("This game is a adventure text based game set in the medieval times")
print ("You will be asked multiple questions with a yes or no response")
print ("you must answer the questions with the answers supplied to you suches as yes or no")
print ("If you don't answer the q uestion with the given answers it will be repeated untill a valid response occurs")
print ("The program can end when you choose")
print ("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
def displayIntro():
#Displays intro to game
print ("\n It's been a rough day in the wild and you despratly need shelter")
print ("There is currently a war going on and nowhere is safe")
print ("But you intend to find somwhere with food and a bed but it wont be easy...")
print ()
def choosePath(lower,middle,upper):
#This functions allows you to choose between multiple options
path = 0
while path < lower or path > upper:
number = input("What path will you take(" + str(lower) + " - " + str(upper) + ")?: ")
if number.isdigit():
path = int (number)
else:
path = 0
return path
def followPath(chosenPath):
print ("you head down a long road\n")
time.sleep(3)
print ("You come across an abandoned campsite and decide to stay there for the night")
time.sleep(3)
print("You wake up to a sudden sound of voices and begin to realise that this campsite wasn't abandoned...")
time.sleep(3)
print("You start to freak out")
time.sleep(3)
if chosenPath == 1:
print("You grab your sword out and decide to go out the tent")
print ("Four well trained knights surround you")
print ("They strike without any hesitation, you counter two knights trying to hit you from the front as two from behind stab you in the back")
print ("The knights decide to burn your body and leave nothing left of you.\n")
elif chosenPath == 2:
print("You dart out of the tent and head for the exit")
print("All the guards try and get you whilst shooting arrows")
print("Several arrows hit you leaving you injured unable to run")
print ("Suddenly a man with a giant axe appears before you and slices you head off in a clean swoop\n")
else chosenPath == 3:
print("You keep calm and decide to sneak past all the guards")
print ("You're close to the exit when suddenly a guard notices you")
print("He's about to call for back up when you dash right into his chest with your sword, leaving it in him and running out the campsite")
print("You make it to a safe forest and decide to rest\n")
displayWelcome()
playAgain = "Y"
while playAgain == "Y":
displayIntro()
choice = choosePath()
followPath(choice)
playAgain = askYesNo ("Would you like to play again?")
print ("\nBye")
Error Number one: line 63, else should be elif or get rid of the condition "chosenPath == 3:
Current state
else chosenPath == 3:
What it should look like
elif chosenPath == 3:
or
else:
The other error is that nothing ever happens on initialization of choice because you forgot to input the "lower, middle, upper" values.
I'm new to this website so please bear with my questioning problems on the website. I need some help to finish off this mini text-based game as homeowork of learning python the hard way book. This is the code I wrote. and I don't know the missing links and what I've done wrong. Help would be appreciated!
from sys import exit
def start():
print "You are in an old temple."
print "There is a door to your right and left or you can walk forwad."
print "Which one do you take?"
choice = raw_input("> ")
if choice == "left":
gold_room()
elif choice == "right":
trap_room()
elif choice == "forward":
monster_room()
else:
dead("you got caught by the ancient gods and you must be killed.")
start()
def monster_room():
print "you're in a room with a monster. what you gonna do?"
choice = raw_input("> ")
if "left" in choice:
print "you are going to the gold room"
gold_room()
elif "right" in choice:
print "you are going to the trap room"
trap_room()
else:
dead("couldnt understand what did you say so you are dead!")
def gold_room():
print "you chose the left room. now you are in a room with a pot of gold!"
print "you can take the pot."
print "or you can just rob the money in it."
print "or you go go to other rooms."
choice = raw_input("> ")
if choice == "take the pot":
print "you are a millionaire from now on!!!"
elif choice == "rob the money":
dead("you will never rest in piece!")
else choice == "another room":
monster_room()
def trap_room():
print "you are now in a trap room."
print "there is a hidden trap in this room."
print "be careful!"
print "you can go back to the monster room"
print "or you can find the trap"
choice = raw_input("> ")
if "find" in choice:
start()
elif "back" in choice:
gold_room()
def dead(why):
print why, "rekt!"
exit(0)
Ok, I've fixed it. Your code has several indentation mistakes, Python requires four spaces or one tab indentation after a def statement.
Another thing is, that you used else with a condition test (else choice == "another room":). That is wrong, it should be elif choice == "another room": or just else.
You also may have noticed, that I changed raw_input() to input(). This converts all inputs to strings (input() will interpret intergers as integers, lists as lists and so on...), and is also more secure.
The last thing is, you run your program (start()) before definign all called functions, this cannot work!
Your code (fixed):
from sys import exit
def start():
print("You are in an old temple.")
print("There is a door to your right and left or you can walk forwad.")
print("Which one do you take?")
choice = input("> ")
if choice == "left":
gold_room()
elif choice == "right":
trap_room()
elif choice == "forward":
monster_room()
else:
dead("you got caught by the ancient gods and you must be killed.")
def monster_room():
print("you're in a room with a monster. what you gonna do?")
choice = input("> ")
if "left" in choice:
print("you are going to the gold room")
gold_room()
elif "right" in choice:
print("you are going to the trap room")
trap_room()
else:
dead("couldn't understand what did you say so you are dead!")
def gold_room():
print("you chose the left room. now you are in a room with a pot of gold!")
print("you can take the pot.")
print("or you can just rob the money in it.")
print("or you go go to other rooms.")
choice = input("> ")
if choice == "take the pot":
print("you are a millionaire from now on!!!")
elif choice == "rob the money":
dead("you will never rest in piece!")
elif choice == "another room":
monster_room()
def trap_room():
print("you are now in a trap room.")
print("there is a hidden trap in this room.")
print("be careful!")
print("you can go back to the monster room")
print("or you can find the trap")
choice = input("> ")
if "find" in choice:
start()
elif "back" in choice:
gold_room()
def dead(why):
print(why, "rekt!")
exit(0)
start()
I would call the start() function at the end, after all the functions you defined. A usual way to write that is to write the following code at the end:
if __name__ == "__main__":
start()
This basically means that the programm runs the start() function at the end, if you're executing the file.
Furthermore you have to leave spaces after defining a function. You wrote:
def monster_room():
print "you're in a room with a monster. what you gonna do?"
but it should be:
def monster_room():
print "you're in a room with a monster. what you gonna do?"
If that didnt help, specify the problem
Sorry for the long code, but I felt that it was important that I include what I was trying to accomplish. I am a beginner with Python and programming in general and I was trying to make a simple text-based adventure game. The game was working good at first until I added the encounter with the bees. I ran the program and I chose to run from the bear, so my hp should be at 40, which was displayed. However, when I chose to swat the bees, my hp should then be at 0 because 40(my current hp)-40=0. My hp is however is displayed at 60, as if the bear encounter never happened. Is there some way I can fix this or is this a limitation in Python?
from sys import exit
from time import sleep
import time
#Hp at start of game:
hp = 100
#The prompt for inputs
prompt = "> "
#Bear encounter
def bear(hp):
choice = raw_input("> ")
if "stand" in choice:
print "The bear walks off, and you continue on your way"
elif "run" in choice:
print "..."
time.sleep(2)
print "The bear chases you and your face gets mauled."
print "You barely make it out alive, however you have sustained serious damage"
hp = hp-60
currenthp(hp)
elif "agressive" in choice:
print "..."
time.sleep(2)
print "The bear sees you as a threat and attacks you."
print "The bear nearly kills you and you are almost dead"
hp = hp-90
currenthp(hp)
else:
print "Well do something!"
bear(hp)
#Bee encounter
def bee(hp):
choice = raw_input(prompt)
if "run" in choice:
print "..."
sleep(2)
print "The bee flies away and you continue on your way."
currenthp(hp)
elif "swat" in choice:
print "..."
sleep(1)
print "You succesfully kill the bee. Good Job!"
sleep(1)
print "Wait a minute"
sleep(2)
print "The bee you killed gives off pheremones, now there are hundreds of bees chasing you."
print "The bees do some serious damage."
hp = hp-40
sleep(1)
currenthp(hp)
else:
print "Well, do something."
bee(hp)
#Function to display the current hp of the current player
def currenthp(hp):
if hp < 100:
print "Your hp is now at %d" % hp
elif hp <= 0:
dead()
else:
print "You are still healthy, good job!"
#Called when player dies
def dead():
print "You sustained too much damage, and as a result have died."
time.sleep(3)
print "GAME OVER!"
print "Would you like to play again?"
choice = raw_input("> ")
if "y" in choice:
start_game()
else:
exit(0)
#Called to Start the Game, useful for restarting the program
def start_game():
print "Welcome to Survival 101"
#START OF GAME
start_game()
print "You start your regular trail."
print "It will be just a little different this time though ;)"
time.sleep(3)
print "You are walking along when suddenly."
time.sleep(1)
print "..."
time.sleep(2)
#Start of first encounter
print "Wild bear appears!."
print "What do you do?"
print "Stand your ground, Run away, be agressive in an attempt to scare the bear"
#first encounter
bear(hp)
#Start of second encounter
print "You continue walking and see a killer bee approaching you"
print "What do you do"
print "run away, swat the bee away"
bee(hp)
You pass hp to functions and inside a function you are updating it, but you are not getting the updated value hp back from the function. You should specify return hp inside the function to return the updated value, and you can store (or update) the updated value in the function call - e.g., hp = bear(hp).
from sys import exit
def start():
print "You woke up in a dungeon"
print "There is three weapon in front of you"
print "A sword, a staff and dagger"
print "Which one do you choose"
choice = raw_input("")
if choice == "dagger":
print "A rogue huh?"
elif choice == "staff":
print "A wizard how interesting..."
elif choice == "sword":
print "A warrior."
else:
print "..."
dungeon_path()
def dungeon_path():
if choice == "dagger":
print "Which way you choose rogue"
start()
I wanna print the last line if I choosed dagger in first function but I can't seem to get it work I tried to give choice a value and then used "if" but it didn't work that way either so what do I do...
You could pass the choice variable as an argument to the dungeon_path function:
...
print "..."
dungeon_path(choice)
def dungeon_path(choice):
if choice == "dagger":
print "Which way you choose rogue"
I'm learning to code through learn python the hard way, and I've recently gotten stuck for the first time. For this exercise we're supposed to write our own game. I did so, but for some reason whenever I run it the right_room() function exits after I put in an answer, instead of proceeding to the next room. Any help would be greatly appreciated. Here's my code:
from sys import exit
def bear_room():
print "You are in a room with a bear."
print "You have two choices. left or right?"
next = raw_input("> ")
if next == "left":
left_room()
elif next == "right":
right_room()
else:
print "No idea what that means..."
def left_room():
print "You went left."
print "There are two doors. right or straight"
next = raw_input("> ")
if next == "right":
bear_room()
elif next == "straight":
second_left()
else:
print "What are you saying, bro?"
def second_left():
print "You went straight."
print "You again have two choices. straight or right?"
next = raw_input("> ")
if next == "straight":
print "You won! Congrats."
exit(0)
elif next == "right":
dead("You opened the door and walked off a cliff. Goodbye!")
else:
print "I didn't quite catch that."
def right_room():
print "You went right."
print "There are two doors. straight or right?"
next == raw_input("> ")
if next == "right":
dead("Oops, a tiger just ate you")
elif next == "straight":
second_right()
else:
"What?!?!?!"
def second_right():
print "You went straight"
print "Nice choice."
print "You have two choices: left or straight"
next == raw_input("> ")
if next == "left":
dead("You just fell 1 million feet to your death.")
elif next == "straight":
print "You made it out alive!"
exit(0)
else:
"WTF?"
def dead(reason):
print reason, "good job!"
exit(0)
def start():
print "You are about to enter a room."
bear_room()
start()
It looks like you're trying to assign to the next variable, but you used the equality check operator (==).