I am trying to do one of the exercises from learn python the hard way and am stuck on something. I created a function and in case one of the statements is fulfilled I would like to put that in another function. This is the outline of how I'm trying to do it:
def room_1():
print "Room 1"
button_push = False
while True:
next = raw_input("> ")
if next == "1":
print "You hear a click but nothing seems to happen."
button_push = True
elif next == "2":
print "You enter room 2"
room_2()
def room_2():
print "Room 2"
while True:
next =raw_input("> ")
if next == "1" and button_push:
print "You can enter Room 3"
room_3()
If button_push is fulfilled then I would like to see that in room_2. Could anyone please help me with that?
You can pass button_push as an argument to the next room:
def room_1():
print "Room 1"
button_push = False
while True:
next = raw_input("> ")
if next == "1":
print "You hear a click but nothing seems to happen."
button_push = True
elif next == "2":
print "You enter room 2"
room_2(button_push) # pass button_push as argument
def room_2(button_push): # Accept button_push as argument
print "Room 2"
while True:
next =raw_input("> ")
if next == "1" and button_push: # button_push is now visible from this scope
print "You can enter Room 3"
room_3()
Related
Hello I am new to python and this is my first stack overflow post, so I apologize if this question has been answered elsewhere (I'm not entirely sure how to search for this topic, feel free to drop a link if it is).
I'm creating an adventure game and I want the user to choose different paths within a house.
I want the user to be able to travel back and forth between room A and room B, however I want different dialogue to appear based on how many times a user has entered room A or room B. If its the first time, I want the function to print (option 1), but if the user enters >1 time i want the function to print (option 2)
I've figured out how to travel back and forth between the 2 rooms, but I don't get different dialogue options if I enter either room >1 times with my current increment code. Does it have to do with the fact that I exit the room_A function when i 'travel to room_B'?
Any help would be greatly appreciated!
def room_A():
room_A_count = 0
# - if this is the first time the user enters the room, this code runs...
if room_A_count == 0:
print ("You enter room A")
print ("What would you like to do?")
print ("1. Enter room B")
print ("2. nothing")
room_A_choice = input("Choice: ")
if room_A_choice = "1":
room_A_count += 1
# - travel to room B
room_B()
elif room_A_choice == "2":
print ("You do nothing")
# - if the user travels back from Room B to Room A, it prints this message...
else:
print ("You enter room A again")
One thing I'd say is that a good principle to generally follow is for functions to behave the same way every time you call them. With that being said, one work around could be to store a room_A_count as a global variable. Then pass it into the function as an argument and increment each time.
That's a bit hacky and seems like it could break easy, so I'd propose an object oriented solution-
class RoomA:
def __init__(self):
self.room_A_count = 0
def enter(self):
if self.room_A_count == 0:
print ("You enter room A")
print ("What would you like to do?")
print ("1. Enter room B")
print ("2. nothing")
room_A_choice = input("Choice: ")
if room_A_choice = "1":
self.room_A_count += 1
# - travel to room B
room_B()
elif room_A_choice == "2":
print ("You do nothing")
else:
print ("You enter room A again")
I'm unable to comment, so I apologize if I understand your question right, all you'll need to do is add an if statement where it checks for room_A_choice
if room_A_choice = ="1":
room_A_count += 1
if room_A_count >= 2:
# do something
else : room_B()
You can use function static variables
def room_A():
if not hasattr(room_A, 'room_A_count'): # check if static variable exists
room_A.room_A_count = 0 # initialize if doesn't set
if room_A.room_A_count == 0: # refers to the funtion static variable
print ("You enter room A")
print ("What would you like to do?")
print ("1. Enter room B")
print ("2. nothing")
room_A_choice = input("Choice: ")
if room_A_choice == "1":
room_A.room_A_count += 1 # incremention function static variable
# - travel to room B
room_B()
elif room_A_choice == "2":
print ("You do nothing")
# - if the user travels back from Room B to Room A, it prints this message...
else:
print ("You enter room A again")
def room_B():
print('In room B')
room_A() # First call
room_A() # Second call
Output
You enter room A
What would you like to do?
1. Enter room B
2. nothing
Choice: 1
In room B
You enter room A again
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 have this code, but I'm not sure how to make it loop, so that after you finish encoding or decoding it brings the menu back up. It's working well right now, just no idea how to loop it.
import string
key = "qetuoadgjlxvnw ryipsfhkzcbm"
abc = "abcdefghijklmnopqrstuvwxyz "
abc_key = string.maketrans(abc, key)
key_abc = string.maketrans(key, abc)
def encode():
"""Encodes input text"""
text = raw_input ("Please enter text to be encoded: ")
text_lower = string.lower(text)
text_lower;
print text_lower.translate(abc_key);
def decode():
"""decyphers code"""
code = raw_input ("Please enter code to be decyphered: ")
code_lower = string.lower(code)
code_lower;
print code_lower.translate(key_abc);
# Welcome message
print "Welcome to Jake's Cryptography program!"
# Print menu
print "SECRET DECODER MENU"
print "0) Quit"
print "1) Encode"
print "2) Decode"
option = raw_input ("What do you want to do?")
if option == "0":
print "Thank you for during secret spy stuff with me!"
elif option == "1":
encode()
elif option == "2":
decode()
else:
print "Sorry, that is not an option."
any help is appreciated!
Wrap it in a while statement. Something like this:
# Welcome message
print "Welcome to Jake's Cryptography program!"
# Print menu
while True:
print "SECRET DECODER MENU"
print "0) Quit"
print "1) Encode"
print "2) Decode"
option = raw_input ("What do you want to do?")
if option == "0":
print "Thank you for during secret spy stuff with me!"
break
elif option == "1":
encode()
elif option == "2":
decode()
else:
print "Sorry, that is not an option."
Notice the break statement!
The above will print the menu each time. If you just want to print the prompt, move the while True: line down after the menu (but before the raw_input line), and then fix your indentation.
# Welcome message here
option = -1
while option != 0:
# Print menu
# Raw input for the next option
# Processing of the options
option = 13
while (int(option) > 0):
option = raw_input ("What do you want to do?")
if option == "0":
print "Thank you for during secret spy stuff with me!"
print "and good night"
elif option == "1":
encode()
elif option == "2":
decode()
else:
print "Sorry, that is not an option."
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("> ")
...