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"
Related
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
I want to know how I can make this code without global variables.
I have tried myself but it seems like it involves return, but then It won't go back to the "menu" (main_list). The point of this code is to always return to the menu except when pressing "3" (exit program).
Sorry for the big (and bad) code, I appreciate all the help I can get.
import sys
word = []
desc = []
def main_list():
print "\nMenu for list \n"
print "1: Insert"
print "2: Lookup"
print "3: Exit program"
choice = raw_input()
print "Choose alternative: ", choice
if choice.isdigit():
choice = int(choice)
if choice == 1:
insert()
elif choice == 2:
look()
elif choice == 3:
sys.exit()
else:
print "Error: Not a valid choice \n", main_list()
else:
print "Error: Not a valid choice \n", main_list()
def insert():
ins = raw_input("Word to insert: ")
if ins not in word:
word.append (ins)
else:
print "Error: Word already exist \n", main_list()
desc.append(raw_input ("Description of word: "))
main_list()
def look():
up = raw_input("Word to lookup: ")
if up not in word:
print "Error: Word not found \n", main_list()
i = 0
while up != word[i]:
i += 1
if up == word[i]:
print "Description of word: ", desc[i]
main_list()
As Xeno said, you need a while loop to continually loop over the input. For your case, I would suggest a do-while loop, but Python does not have a built-in do-while, so you will need to emulate one, possibly something like this:
while True:
# do stuff
if condition:
break
To get rid of the global variables, you will need to pass variables into your methods and return out of them.
def insert(word, desc):
# do stuff
Now, I noticed you call main_list() at the end of insert() and look(). Do not do this. You do not need a new instance every time, you need to return back to the current instance. So, set up something like this:
def main_list():
# do stuff
while True:
# do more stuff
if condition:
break
# do more stuff
def insert():
# do stuff - return any new value; otherwise, just let it auto-return
def look():
# do stuff - return any new value; otherwise, just let it auto-return
It looks like you should use a while loop in your main function, so that it will only exit when you want it to:
So something like this:
while choice != 3:
if choice == 1:
insert()
elif choice == 2:
look()
elif choice == 3:
sys.exit()
else:
print "Error: Not a valid choice \n"
print "1: Insert"
print "2: Lookup"
print "3: Exit Program"
choice = int(raw_input("choose alternative")
Edit: As Prune so nicely stated below, I did not give any reasoning for my answer, so here goes:
The reason your code wasn't going back to the loop you wanted to, is that you are using an if-statement to run your loop. A while loop will allow you to repeat the desired process until you need to break. And if you want a reason not to use the main_list() function called from your other functions, look at Hosch250's answer
First of all, clean up that main loop as the previous "answer" suggests: delete the exit clause and just leave the while loop when you're done.
Second, pass word and desc in the parameter list. Add them to the "def" lines in your functions.
Third, remove the calls to main_list from your print statements; you'll return to the main program when you run off the bottom of the function.
Does this get you moving?
word = []
desc = []
menu = \
"\nMenu for list \n" \
"1: Insert\n" \
"2: Lookup\n" \
"3: Exit program"
choice = raw_input(menu)
while choice != 3:
if choice.isdigit():
choice = int(choice)
if choice == 1:
insert(word, desc)
elif choice == 2:
look(word, desc)
else:
print "Error: Not a valid choice \n", main_list()
else:
print "Error: Not a valid choice \n", main_list()
Probably the simplest thing to do with your existing code would be to restructure it something like this, which makes main_list() drive the whole process by adding a while loop to it, and have it just pass the shared variables to each of the other functions as arguments.
def main_list():
word = []
desc = []
print "\nMenu for list"
print " 1: Insert"
print " 2: Lookup"
print " 3: Exit program"
while True:
choice = raw_input()
print "Alternative chosen: ", choice
if choice.isdigit():
choice = int(choice)
if choice == 1:
insert(word, desc)
elif choice == 2:
look(word, desc)
elif choice == 3:
break
else:
print "Error: Not a valid choice"
else:
print "Error: Not a valid choice"
def insert(word, desc):
ins = raw_input("Word to insert: ")
if ins not in word:
word.append(ins)
else:
print "Error: Word already exist"
desc.append(raw_input("Description of word: "))
def look(word, desc):
up = raw_input("Word to lookup: ")
if up not in word:
print "Error: Word not found"
i = 0
while up != word[i]:
i += 1
if up == word[i]:
print "Description of word: ", desc[i]
main_list()
Encapsulate it in a class. This way the word list can be held within the class instance. It's not global and you don't need to pass it around.
class main_list(object):
def __init__(self):
self.words = {}
def run(self):
while(True):
print "\nMenu for list \n"
print "1: Insert"
print "2: Lookup"
print "3: Exit program"
choice = raw_input()
print "Chose alternative: ", choice
if choice.isdigit():
choice = int(choice)
if choice == 1:
self.insert()
elif choice == 2:
self.look()
elif choice == 3:
break
else:
print "Error: Not a valid choice"
else:
print "Error: Not a valid choice"
def insert(self):
ins = raw_input("Word to insert: ").lower()
if ins not in self.words:
desc = raw_input("Enter description of word: ")
self.words[ins] = desc
else:
print "Error: Word already exist"
def look(self):
up = raw_input("Word to lookup: ").lower()
if up in self.words:
print "description of `%s` is `%s`" % (up, self.words[up])
else:
print "Error: Word %s not found" % up
ml = main_list()
ml.run()
Note that I changed to code to use a dictionary. This will avoid needing two separate lists to hold word and description and give faster look ups.
def main_menu():
print ("Three Doors Down Figurative Language Game")
print ("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*")
print ("NOTE: TO SELECT, TYPE NUMBER OF OPTION")
print ("")
print (" 1) Begin Game")
print ("")
print (" 2) Options")
print ("")
print ("")
menu_selection()
def menu_selection():
valid_answer = ["1","2"]
user_choice = str(input("Make a choice.."))
if user_choice in valid_answer:
def check_valid(user_choice):
if user_choice == 1: #Error section V
return("You started the game.")
else:
user_choice != 1
return("Credits to ____, created by ____")
check_valid(user_choice) #Error Section ^
else:
print("Please use an actual entry!")
menu_selection()
def enterText():
print("ENTER ANSWER!")
print (main_menu())
Okay, so the error should be labeled. That specific if/else statment shows up as "None" and I have tried every method to fix it. One method worked for the if/else statement on the outside, but not this one.
You're taking input as a string str(input()). Then, you're checking if user_input == 1; testing to see if it is an integer, even though it is a string. Instead, try converting to an integer using int(input()). Also, the line user_input != 1 is unnecessary, it's just the equivalent of writing True in your code. Furthermore, you define a function in your if statement, which shouldn't be there:
def main_menu():
print ("Three Doors Down Figurative Language Game")
print ("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*")
print ("NOTE: TO SELECT, TYPE NUMBER OF OPTION")
print ("")
print (" 1) Begin Game")
print ("")
print (" 2) Options")
print ("")
print ("")
menu_selection()
def menu_selection():
valid_answer = ["1","2"]
user_choice = int(input("Make a choice.."))
if user_choice in valid_answer:
if user_choice == 1:
return("You started the game.")
else:
return("Credits to ____, created by ____")
check_valid(user_choice)
else:
print("Please use an actual entry!")
menu_selection()
def enterText():
print("ENTER ANSWER!")
print (main_menu())
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 (==).
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("> ")
...