I am trying to make a simple game.
The logic is like this: "There are five doors, each numbered 1 to 5. Users will be asked to input any one number. For example, if they enter "1", the GoldRoom will be opened (and the associated class will be processed)."
Now, I have defined one class, GoldRoom(), and for testing, entered "1". The processing happens as expected. However, when I enter "2" as my choice, the processing still happens, instead of the print statement, i.e the else statement is not getting executed.
Where am I going wrong?
#################################
# Learning to make a game#
#################################
# An attempt to make a game
# Each room will be described by a class, whose base class will be Room
# The user will be prompted to enter a number, each number will be assigned with a Room in return
from sys import exit
print "Enter your choice:"
room_chosen = int(raw_input("> "))
if room_chosen == 1:
goldroom = GoldRoom()
goldroom.gold_room()
def dead(why):
print "why, Good Job!"
exit(0)
#class Room(object): #the other room will be derived of this
# pass
class Room(object):
pass
class GoldRoom(Room):
# here the user will be asked with question on how much Gold he wants
print"This room is full of gold. How much do you take!"
next = raw_input("> ")
if "0" in next or "1" in next:
how_much = int(next)
print how_much
else:
dead("Man, learn to type some number")
if how_much < 50:
print "Nice, you are not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
#class KoiPondRoom(Room):
# in this room, the user will be made to relax
#class Cthulhu_Room(Room):
# sort of puzzle to get out
#class Bear_Room(Room):
# bear room
#class Dark_Room(Room):
# Dark Room, will be turned into Zombie
#class Dead_Room(Room):
# Those who enter here would be dead
if room_chosen == 1:
goldroom = GoldRoom()
goldroom.gold_room()
else:
print "YOU SUCK!"
the problem is here:
class GoldRoom(Room):
# here the user will be asked with question on how much Gold he wants
print"This room is full of gold. How much do you take!"
as the whole source loaded into python vm, this piece of code is executed, and it print some thing, you should change it to:
class GoldRoom(Room):
# here the user will be asked with question on how much Gold he wants
def gold_room(self):
print"This room is full of gold. How much do you take!"
next = raw_input("> ")
if "0" in next or "1" in next:
how_much = int(next)
print how_much
else:
dead("Man, learn to type some number")
if how_much < 50:
print "Nice, you are not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
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
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.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I have some codes below, the choice takes only integer input but prints out something special if the input is not an integer. However, the codes below to treat this issue seems a little bit lengthy. Anyway to fix it?
from sys import exit
def gold_room():
print "This room is full of gold. How much do you take?"
choice = raw_input("> ")
if "0" in choice or "1" in choice or "2" in choice or "3" in choice or "4" in choice or "5" in choice or "6" in choice or "7" in choice or "8" in choice or "9" in choice:
how_much = int(choice)
else:
dead("Man, learn to type a number.")
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(1)
else:
dead("You're greedy!")
def dead(why):
print why, "Good job!"
exit(0)
gold_room()
Try something like:
try:
how_much = int(choice)
except ValueError:
dead('Man, learn to type a number.')
and look up Easier to ask for forgiveness than permission for the rationale.
You can use the str.isdigit() to check if its a number, using try...except statement for this is not recommended because it makes your code messy and could cause errors in the long run. But if it's only that it'll work too.
from sys import exit
def gold_room():
print "This room is full of gold. How much do you take?"
choice = raw_input("> ")
if choice.isdigit(): #Checks if it's a number
how_much = int(choice)
else:
dead("Man, learn to type a number.")
return
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(1)
else:
dead("You greedy bastard!")
def dead(why):
print why, "Good job!"
exit(0)
gold_room()
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
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("> ")
...