I'm new to programming. I'm learning python from here. I am on lesson 36 which says to make a small game. This is the game:
from sys import exit
def you_won():
print """
CONGRATUFUCKINGLATIONS!!!
You won this really easy but kind of cool game.
This is my first game but not the last.
Thanks for playing.
Do you want to start over? Yes or No?
"""
next = raw_input("> ")
if next == "Yes" or "yes":
start()
elif next == "No" or "no":
exit(0)
else:
try_again()
def try_again(function_name):
print "That doesn't make sense, try again."
function_name()
def youre_dead():
print "You died, do you want to start over? Yes or No?"
next = raw_input("> ")
if next == "Yes" or "yes":
start()
elif next == "No" or "no":
exit(0)
else:
try_again()
def main_room():
print """
You enter a grand room with a throne in the back.
Standing right in front of you is the Qurupeco.
He snarls at you and you bare your teeth.
You can:
1 Attack Qurupeco
2 Taunt Qurupeco
3 Run Away
"""
if has_dynamite == True:
print "A Use Dynamite"
if has_sword == True:
print "B Use Sword"
if has_bow == True:
print "C Use Bow"
next = raw_input("> ")
if next == "1":
"You attack the Qurupeco but he stabs you and carves your heart out with a spoon."
youre_dead()
elif next == "2":
"You taunt the Qurupeco and he bites off your legs and lets you bleed to death."
youre_dead()
elif next == "3":
print "You try to run away but the Qurupeco is too fast. He runs you down and eats your entire body."
youre_dead()
elif next == "A" or "a":
print "You throw a stick of dynamite into his mouth and it blows him into tiny marshmallow size pieces."
you_won()
elif next == "B" or "b":
"You slice him squarely in two equal pieces."
you_won()
elif next == "C":
"You shoot him with your bow right between the eyes."
you_won()
def rightdoor_smallway():
print """
You go in the left door and see a lever at at the end of the room.
The flooring looks weird in this room.
You can:
1 Pull Lever
2 Leave
"""
next = raw_input("> ")
if next == "1":
print """
You pull the lever and feel the floor rush from beneath your feet.
You fall for a while and land head first on a giant spike.
"""
youre_dead()
if next == "2":
main_room()
def open_bow_chest():
print "You open the chest and find a bow and some arrows."
print "You take them and leave."
has_bow = True
main_room()
return has_bow
def leftdoor_smallway():
print """
You open the door to your left and see a chest.
You can:
1 Open Chest
2 Leave
"""
next = raw_input("> ")
if next == "1":
open_bow_chest()
elif next == "2":
main_room()
else:
try_again()
def forward_threeway():
print """
You walk forward for a while until you see two doors.
There is one to your right and one to your left.
You can:
1 Go Right
2 Go Left
3 Go Forward
Note: If you go left, you can't go right.
"""
next = raw_input("> ")
if next == "1":
rightdoor_smallway()
elif next == "2":
leftdoor_smallway()
elif next == "3":
main_room()
def three_way2():
forward_threeway()
def reason_meanman():
print """
You try to get the man to leave the damsel alone but he refuses.
When you insist he gets mad and snaps your neck.
"""
youre_dead()
def flirt_damsel():
print """
You flirt with the damsel, one thing leads to another and you end up having sex.
It was great.
Afterwards you tell her to wait for you there and you leave to finish your mission.
"""
three_way2()
def free_damsel():
print "You unchain the damsel, tell her where your king's castle is, and then leave."
three_way2()
def punch_meanman():
print """
You punch the mean man and he falls through a large random spike.
Ouch.
The damsel says thank you and tries her best to be seductive.
You can:
1 Flirt With Her
2 Free Her
3 Leave Her There
"""
next = raw_input("> ")
if next == "1":
flirt_damsel()
elif next == "2":
free_damsel()
elif next == "3":
three_way2()
else:
try_again()
def left_threeway():
print """
You go left for what seems like forever and finally see a door on the right.
You enter the room and see a mean looking man terrorizing a damsel that is chained to a post.
You can:
1 Reason With Mean Man
2 Punch Mean Man
3 Run Away
"""
next = raw_input("> ")
if next == "1":
reason_meanman()
elif next == "2":
punch_meanman()
elif next == "3":
three_way2()
else:
try_again()
def attack_gorilla():
print "You run at the gorilla and he bites your head off."
youre_dead()
def taunt_gorilla():
print """
You taunt the gorilla and he runs at you.
You trip him and he smacks his head into the wall so hard that he dies.
You can:
1 Leave
2 Open Chest
"""
next = raw_input("> ")
if next == "1":
three_way2()
elif next == "2":
print "You open the chest, find a sword, take it, and leave."
has_sword = True
three_way2()
else:
try_again()
return has_sword
def right_threeway():
print """
You go right for what seems like forever and finally find a door.
You enter the room and see a giant gorilla gaurding a chest.
You can:
1 Attack Gorilla
2 Taunt Gorilla
3 Run Away
"""
next = raw_input("> ")
if next == "1":
attack_gorilla()
elif next == "2":
taunt_gorilla()
elif next == "3":
three_way2()
else:
try_again()
def back_threeway():
print """
You walk outside and hear a click sound.
You try to open the door but it is now locked.
You freeze to death.
"""
youre_dead()
def three_way1():
print """
You enter the castle and see long hallways in every direction but behind you.
You can:
1 Go Forward
2 Go Left
3 Go Right
4 Go Back
Note: You can only pick one of the last three.
"""
next = raw_input("> ")
if next == "1":
forward_threeway()
elif next == "2":
left_threeway()
elif next == "3":
right_threeway()
elif next == "4":
back_threeway()
else:
try_again()
def go_inside():
print "You go back to the entrance, open the door, and go inside."
three_way1()
def poison_chest():
print "You struggle with the chest for a minute and finally figure out the mechanism, but, unfortunately, a poisonous gas is released and you die in agony."
youre_dead()
def outside_left():
print """
You go to the right and see a treasure chest three meters forward.
You can:
1 Go Inside
2 Open Chest
"""
next = raw_input("> ")
if next == "1":
turnback_outside()
elif next == "2":
poison_chest()
else:
try_again(outside_left)
def dynamite_inside():
print "You take the dynamite, it may be useful."
has_dynamite = True
go_inside()
return has_dynamite
def outside_right():
print """
You go left and see a stick of dynamite laying on the ground.
You can:
1 Go inside
2 Take Dynamite
"""
next = raw_input("> ")
if next == "1":
go_inside()
elif next == "2":
dynamite_inside()
else:
try_again(outside_right)
def start():
print """
You are a knight in shining armor, you lost your sword on the way here.
You have come to destroy the evil Qurupeco.
You are at the cold entrance to the Qurupeco's castle.
To the right of the entrance is a sign that reads: "Enter at your own risk!"
The walls are made of extremely tough stone.
You can:
1 Enter Castle
2 Go Left
3 Go Right
What do you do?
Note: You can't go left and right.
Note: Enter numbers when you're asked what you want to do.
"""
has_dynamite = False
has_sword = False
has_bow = False
next = raw_input("> ")
if next == "1":
three_way1()
elif next == "2":
outside_left()
elif next == "3":
outside_right()
else:
try_again(start)
return has_dynamite, has_sword, has_bow
start()
This is me playing the game and getting an error that I cant figure out.
jacob#HP-DX2450:~/Documents$ python ex36.py
You are a knight in shining armor, you lost your sword on the way here.
You have come to destroy the evil Qurupeco.
You are at the cold entrance to the Qurupeco's castle.
To the right of the entrance is a sign that reads: "Enter at your own risk!"
The walls are made of extremely tough stone.
You can:
1 Enter Castle
2 Go Left
3 Go Right
What do you do?
Note: You can't go left and right.
Note: Enter numbers when you're asked what you want to do.
> 3
You go left and see a stick of dynamite laying on the ground.
You can:
1 Go inside
2 Take Dynamite
> 2
You take the dynamite, it may be useful.
You go back to the entrance, open the door, and go inside.
You enter the castle and see long hallways in every direction but behind you.
You can:
1 Go Forward
2 Go Left
3 Go Right
4 Go Back
Note: You can only pick one of the last three.
> 1
You walk forward for a while until you see two doors.
There is one to your right and one to your left.
You can:
1 Go Right
2 Go Left
3 Go Forward
Note: If you go left, you can't go right.
> 3
You enter a grand room with a throne in the back.
Standing right in front of you is the Qurupeco.
He snarls at you and you bare your teeth.
You can:
1 Attack Qurupeco
2 Taunt Qurupeco
3 Run Away
Traceback (most recent call last):
File "ex36.py", line 368, in <module>
start()
File "ex36.py", line 362, in start
outside_right()
File "ex36.py", line 331, in outside_right
dynamite_inside()
File "ex36.py", line 316, in dynamite_inside
go_inside()
File "ex36.py", line 290, in go_inside
three_way1()
File "ex36.py", line 278, in three_way1
forward_threeway()
File "ex36.py", line 140, in forward_threeway
main_room()
File "ex36.py", line 47, in main_room
if has_dynamite == True:
NameError: global name 'has_dynamite' is not defined
jacob#HP-DX2450:~/Documents$
Any ideas?
The problem is arising due to
variable scope
You can check this question as well to clear your doubt regarding global or local scope:-
Python global/local variables
The variable
has_dynamite
is defined only inside the
start()
function. Therefore, it has only a local scope, to make it global define has_dynamite outside any functions and write your functions like this
def start():
global has_dynamite
Do this for all of the functions which use has_dynamite variable.
You can also pass the has_dynamite variable as a parameter to the function. ie instead of typing the above mentioned code, you can type
start(has_dynamite)
while calling the function, but be sure you include this parameter in the function definition also, otherwise it will show you an error
Here is the corrected code:-
from sys import exit
has_dynamite = True
has_sword = True
has_bow = True
def you_won():
print """
CONGRATUFUCKINGLATIONS!!!
You won this really easy but kind of cool game.
This is my first game but not the last.
Thanks for playing.
Do you want to start over? Yes or No?
"""
next = raw_input("> ")
if next == "Yes" or "yes":
start()
elif next == "No" or "no":
exit(0)
else:
try_again()
def try_again(function_name):
print "That doesn't make sense, try again."
function_name()
def youre_dead():
print "You died, do you want to start over? Yes or No?"
next = raw_input("> ")
if next == "Yes" or "yes":
start()
elif next == "No" or "no":
exit(0)
else:
try_again()
def main_room():
global has_dynamite
global has_sword
global has_bow
print """
You enter a grand room with a throne in the back.
Standing right in front of you is the Qurupeco.
He snarls at you and you bare your teeth.
You can:
1 Attack Qurupeco
2 Taunt Qurupeco
3 Run Away
"""
if has_dynamite == True:
print "A Use Dynamite"
if has_sword == True:
print "B Use Sword"
if has_bow == True:
print "C Use Bow"
next = raw_input("> ")
if next == "1":
"You attack the Qurupeco but he stabs you and carves your heart out with a spoon."
youre_dead()
elif next == "2":
"You taunt the Qurupeco and he bites off your legs and lets you bleed to death."
youre_dead()
elif next == "3":
print "You try to run away but the Qurupeco is too fast. He runs you down and eats your entire body."
youre_dead()
elif next == "A" or "a":
print "You throw a stick of dynamite into his mouth and it blows him into tiny marshmallow size pieces."
you_won()
elif next == "B" or "b":
"You slice him squarely in two equal pieces."
you_won()
elif next == "C":
"You shoot him with your bow right between the eyes."
you_won()
def rightdoor_smallway():
print """
You go in the left door and see a lever at at the end of the room.
The flooring looks weird in this room.
You can:
1 Pull Lever
2 Leave
"""
next = raw_input("> ")
if next == "1":
print """
You pull the lever and feel the floor rush from beneath your feet.
You fall for a while and land head first on a giant spike.
"""
youre_dead()
if next == "2":
main_room()
def open_bow_chest():
global has_bow
print "You open the chest and find a bow and some arrows."
print "You take them and leave."
has_bow = True
main_room()
return has_bow
def leftdoor_smallway():
print """
You open the door to your left and see a chest.
You can:
1 Open Chest
2 Leave
"""
next = raw_input("> ")
if next == "1":
open_bow_chest()
elif next == "2":
main_room()
else:
try_again()
def forward_threeway():
print """
You walk forward for a while until you see two doors.
There is one to your right and one to your left.
You can:
1 Go Right
2 Go Left
3 Go Forward
Note: If you go left, you can't go right.
"""
next = raw_input("> ")
if next == "1":
rightdoor_smallway()
elif next == "2":
leftdoor_smallway()
elif next == "3":
main_room()
def three_way2():
forward_threeway()
def reason_meanman():
print """
You try to get the man to leave the damsel alone but he refuses.
When you insist he gets mad and snaps your neck.
"""
youre_dead()
def flirt_damsel():
print """
You flirt with the damsel, one thing leads to another and you end up having sex.
It was great.
Afterwards you tell her to wait for you there and you leave to finish your mission.
"""
three_way2()
def free_damsel():
print "You unchain the damsel, tell her where your king's castle is, and then leave."
three_way2()
def punch_meanman():
print """
You punch the mean man and he falls through a large random spike.
Ouch.
The damsel says thank you and tries her best to be seductive.
You can:
1 Flirt With Her
2 Free Her
3 Leave Her There
"""
next = raw_input("> ")
if next == "1":
flirt_damsel()
elif next == "2":
free_damsel()
elif next == "3":
three_way2()
else:
try_again()
def left_threeway():
print """
You go left for what seems like forever and finally see a door on the right.
You enter the room and see a mean looking man terrorizing a damsel that is chained to a post.
You can:
1 Reason With Mean Man
2 Punch Mean Man
3 Run Away
"""
next = raw_input("> ")
if next == "1":
reason_meanman()
elif next == "2":
punch_meanman()
elif next == "3":
three_way2()
else:
try_again()
def attack_gorilla():
print "You run at the gorilla and he bites your head off."
youre_dead()
def taunt_gorilla():
print """
You taunt the gorilla and he runs at you.
You trip him and he smacks his head into the wall so hard that he dies.
You can:
1 Leave
2 Open Chest
"""
next = raw_input("> ")
if next == "1":
three_way2()
elif next == "2":
print "You open the chest, find a sword, take it, and leave."
has_sword = True
three_way2()
else:
try_again()
return has_sword
def right_threeway():
print """
You go right for what seems like forever and finally find a door.
You enter the room and see a giant gorilla gaurding a chest.
You can:
1 Attack Gorilla
2 Taunt Gorilla
3 Run Away
"""
next = raw_input("> ")
if next == "1":
attack_gorilla()
elif next == "2":
taunt_gorilla()
elif next == "3":
three_way2()
else:
try_again()
def back_threeway():
print """
You walk outside and hear a click sound.
You try to open the door but it is now locked.
You freeze to death.
"""
youre_dead()
def three_way1():
print """
You enter the castle and see long hallways in every direction but behind you.
You can:
1 Go Forward
2 Go Left
3 Go Right
4 Go Back
Note: You can only pick one of the last three.
"""
next = raw_input("> ")
if next == "1":
forward_threeway()
elif next == "2":
left_threeway()
elif next == "3":
right_threeway()
elif next == "4":
back_threeway()
else:
try_again()
def go_inside():
print "You go back to the entrance, open the door, and go inside."
three_way1()
def poison_chest():
print "You struggle with the chest for a minute and finally figure out the mechanism, but, unfortunately, a poisonous gas is released and you die in agony."
youre_dead()
def outside_left():
print """
You go to the right and see a treasure chest three meters forward.
You can:
1 Go Inside
2 Open Chest
"""
next = raw_input("> ")
if next == "1":
turnback_outside()
elif next == "2":
poison_chest()
else:
try_again(outside_left)
def dynamite_inside():
global has_dynamite
print "You take the dynamite, it may be useful."
has_dynamite = True
go_inside()
return has_dynamite
def outside_right():
print """
You go left and see a stick of dynamite laying on the ground.
You can:
1 Go inside
2 Take Dynamite
"""
next = raw_input("> ")
if next == "1":
go_inside()
elif next == "2":
dynamite_inside()
else:
try_again(outside_right)
def start():
global has_dynamite
global has_sword
global has_bow
print """
You are a knight in shining armor, you lost your sword on the way here.
You have come to destroy the evil Qurupeco.
You are at the cold entrance to the Qurupeco's castle.
To the right of the entrance is a sign that reads: "Enter at your own risk!"
The walls are made of extremely tough stone.
You can:
1 Enter Castle
2 Go Left
3 Go Right
What do you do?
Note: You can't go left and right.
Note: Enter numbers when you're asked what you want to do.
"""
has_dynamite = False
has_sword = False
has_bow = False
next = raw_input("> ")
if next == "1":
three_way1()
elif next == "2":
outside_left()
elif next == "3":
outside_right()
else:
try_again(start)
return has_dynamite, has_sword, has_bow
start()
I hope this helps
has_dynamite is not global but local variable. It exists only in start()
Put it outside all functions to make it global.
has_dynamite = False
has_sword = False
has_bow = False
start()
Now you can get value of has_dynamite in any function
But if you need to change global value you have to use global keyword
def dynamite_inside():
global has_dynamite
print "You take the dynamite, it may be useful."
has_dynamite = True
go_inside()
# return has_dynamite # unusable line
Related
I've being making a small escape room project and when you complete an action it's supposed to loop upon completion of certain actions it is supposed to loop but my code won't do that. Can someone help me fix it? This is my code. Link: (https://replit.com/#HoloGrain/Escape-Room-or-Bigger-Project#main.py)
inventory= []
HP=100
ImplacedAnemo= False
ImplacedGeo= False
ImplacedElectro= False
print("Type every word beggining with a capital letter")
def Help():
print("Commands:")
print("Pick Up (Item))")
print("Throw (Item) At (Other item)")
print("Press (Item)")
print("Hit (Item)")
print("Open (Place)")
print("Use (Item), (Command can only be used in battles)")
print("Use (Item) On (Item or Door(ex. Room 1 Door))")
print("Inventory", "(Opens inventory)")
print("Check HP", "(Checks HP)")
def start():
print("Welcome to HoloGrain's Escape room")
print("You are locked in Tenshukaku")
def Room1():
print("Paimon: Where are we")
print("You: I don't know")
print("Paimon: We should get out")
def Room1Command():
ChainsLocked = True
print("Room 1 Tools: Glass cage (contains sword), Paimon (If you get hungry and talks), Rock, Door (locked using a sword lock), Chains (Locked using sword lock)")
print("You're chained to the floor")
Room1Start = input("What do you want to do?: ")
if Room1Start == "Pick Up Rock":
for x in inventory:
if x == "Rock":
print("Action: Hey, don't even try")
Room1Command()
elif x == "Dull Blade":
print("Hey, don't even try")
Room1Command()
else:
inventory.append("Rock")
print("You have picked up a rock")
Room1Command()
elif Room1Start == "Throw Rock At Glass Cage":
for x in inventory:
if x == "Rock":
print("Action: You succesfully threw the rock it shatters the cage and you get the dull blade (6 DMG) and can ")
inventory.remove('Rock')
inventory.append("Dull Blade")
else:
print("You don't have a Rock to throw")
elif Room1Start == "Use Dull Blade On Chains":
for x in inventory:
if x == "Dull Blade":
if ChainsLocked == True:
ChainLocked = False
inventory.append("Chains")
print("You have unlocked the chains (Can stop one attack from an enemy and restarts mega-skills cooldown (One-time use)) and taken them")
else:
print("Action: You've done this already")
elif Room1Start == "Check HP":
print(HP)
Room1Command()
elif Room1Start == "Check Inventory":
print(inventory)
Room1Command()
elif Room1Start == "Use Dull Blade On Door":
for x in inventory:
if x == "Dull Blade":
if ChainLocked == False:
print("You've opened the door")
else:
print("That doesn't work")
else:
print("Action: Undefined action in current state")
Room1Command()
Help()
start()
Room1()
Room1Command()
Fo
elif Room1Start == "Throw Rock At Glass
You don't have a "Room1Commande() at the end
So the first thing I see is that you're looping through an empty list - so that's not happening.
Perhaps you mean something like this:
def Room1Command():
ChainsLocked = True
print(
"Room 1 Tools: Glass cage (contains sword), Paimon (If you get hungry and talks), Rock, Door (locked using a sword lock), Chains (Locked using sword lock)"
)
print("You're chained to the floor")
Room1Start = input("What do you want to do?: ")
if Room1Start == "Pick Up Rock":
if len(inventory) == 0 or "Rock" not in inventory:
inventory.append("Rock")
print("You have picked up a rock")
Room1Command()
else:
do_something_else()
There isn't any loop in your code. It just calls all the functions once, and it's over.
If you want the Room1Command to be always running, you can just easily add Room1Command() in the last line of Room1Command function. So it would look like this :
def Room1Command():
ChainsLocked = True
print("Room 1 Tools: Glass cage (contains sword), Paimon (If you get hungry and talks), Rock, Door (locked using a sword lock), Chains (Locked using sword lock)")
print("You're chained to the floor")
Room1Start = input("What do you want to do?: ")
if Room1Start == "Pick Up Rock":
for x in inventory:
if x == "Rock":
print("Action: Hey, don't even try")
Room1Command()
elif x == "Dull Blade":
print("Hey, don't even try")
Room1Command()
else:
inventory.append("Rock")
print("You have picked up a rock")
Room1Command()
elif Room1Start == "Throw Rock At Glass Cage":
for x in inventory:
if x == "Rock":
print("Action: You succesfully threw the rock it shatters the cage and you get the dull blade (6 DMG) and can ")
inventory.remove('Rock')
inventory.append("Dull Blade")
else:
print("You don't have a Rock to throw")
elif Room1Start == "Use Dull Blade On Chains":
for x in inventory:
if x == "Dull Blade":
if ChainsLocked == True:
ChainLocked = False
inventory.append("Chains")
print("You have unlocked the chains (Can stop one attack from an enemy and restarts mega-skills cooldown (One-time use)) and taken them")
else:
print("Action: You've done this already")
elif Room1Start == "Check HP":
print(HP)
Room1Command()
elif Room1Start == "Check Inventory":
print(inventory)
Room1Command()
elif Room1Start == "Use Dull Blade On Door":
for x in inventory:
if x == "Dull Blade":
if ChainLocked == False:
print("You've opened the door")
else:
print("That doesn't work")
else:
print("Action: Undefined action in current state")
Room1Command()
Room1Command()
By doing this, everytime the user enters a command and it gets processed, your code will be waiting for the next input. Which means there would be a loop on your Room1Command function. If I've understood your issue properly, I think this would work.
Also keep in mind that the list called Inventory is empty, so you can't iterate over it. You should put some values inside it first.
I created a text based RPG using Python. At the moment when you execute the program it brings you through an introduction and at the end of it i have the user decide to go 1.Left 2. Right 3. Middle. Each place has a unique item needed to complete the game, meaning if you go to the right it will see if you have a specific item appended to your bag. If you do not have it you will return to the main part to decide where to go again. That being said the middle is the main part where i want the user to be able to attack a dragon right away so they can lose, or if prepared with the necessary items appended, win! Now you do not have the option to attack, you just get to the dragon and win, so there is no lose. Any tips of how to incorporate an input throughout the game would be helpful. If more information is needed i can gladly share :).
I tried implementing an input before attacking the dragon but it got caught inside the loop so even when you obtained all the items you would get returned to the main dungeon. Here is a snippet code for the final dungeon for an idea.
def valid_input(prompt, option1, option2):
while True:
response = input(prompt).lower()
if option1 in response:
print_pause("You use the " + str(Weapon) + " against the dragon")
print_pause("But it is not strong enough "
"to defeat the dragon, he uses Fire Breath"
" and, he incinerates you! ")
print_pause("You lose!")
play_again()
break
elif option2 in response:
print_pause("Smart Choice! You head back to the main dungeon")
dungeon_game()
break
else:
print("Sorry, try again")
return response
def middle_dungeon():
print_pause("You go to the middle dungeon.")
print_pause("After a few moments,"
" you find yourself in front of a " + Dragon + "!")
print_pause("This is why you need these magical powers.")
if "MagicRune" in bag:
print_pause("Luckily the Wizard trained you well, you now obtain "
" the power of the " + str(MagicRune) + "!")
print_pause("You attack the dragon! ")
if "MagicRune" not in bag:
print_pause("You do not obtain the necessary magical powers.")
print_pause("It looks like you need a scroll or more power!.")
print_pause("You head back to the main dungeon.")
dungeon_game()
dragon_health = 100
count = 0
while dragon_health > 0:
damage_by_player = random.randint(0, 60)
print_pause(f"You hit the dragon and caused {damage_by_player} damage")
dragon_health = dragon_health - damage_by_player
print_pause(f"dragon health is now {dragon_health}")
count = count + 1
print_pause(f"You successfully defeated the dragon in {count} attempts, you win!")
play_again()
def dungeon_game():
passage = ''
if 'started' not in Dungeon:
display_intro()
Dungeon.append('started')
while passage != '1' and passage != '2' and passage != '3':
passage = input("1. Left\n"
"2. Right\n"
"3. Middle\n")
if passage == '1':
left_dungeon()
elif passage == '2':
right_dungeon()
elif passage == '3':
middle_dungeon()
dungeon_game()
So essentially this output will deny you until you go to the left dungeon and right dungeon, where you see MagicRune in bag: this will let you go to the dragon while loop and win the game.
You need to rearrange your code a bit. Here's how you could change your input function:
def valid_input(prompt, option1, option2):
while True:
response = input(prompt).lower()
if option1 in response:
return option1
elif option2 in response:
return option2
else:
print("Sorry, try again")
Now it returns the option the user chose and lets the calling code determine what to do with that information. This makes it actually reusable. You'd call it like this:
chosen = valid_input("Wanna attack the dragon?", "yes", "no")
if chosen == "yes":
# do that stuff
else:
# do other stuff
You also have another problem that you really need to fix: you are treating function calls like goto statements. This will cause you pain when you're trying to debug your code, and also causes hard-to-track bugs.
For example, you should not call play_again() to restart your code. Instead, set up your code structure so that you don't have to do that. E.g.
def dungeon_game():
while True:
# set up initial game state here, e.g.
bag = ["sword", "potion"]
# call main game logic function
dungeon()
# that function returned, so the game is over.
want_to_play = input("play again?")
if want_to_play == "no":
# if we don't break, the While loop will start the game again
break
def dungeon():
# blah blah dragon attack
if (whatever):
print("You got killed. Game over.")
return # goes back to dungeon_game()
else:
print("You won the fight")
# code for the next thing that happens...
if __name__ == "__main__":
dungeon_game()
I'm pretty new to programming, but I've got a quick question. I'm trying to write a sort of "choose your own adventure" game, but I've run into a problem. I'm only really as far into if statements in the code, but I want to be able to send the user back to previous code when they type something.
For example:
print "You are in a room with two doors to either side of you."
choiceOne = raw_input("Which way will you go?")
choiceOne = choiceOne.lower()
if choiceOne = "r" or choiceOne = "right":
print "You go through the right door and find yourself at a dead end."
elif choiceOne = "l" or choiceOne = "left":
print "You go through the left door and find yourself in a room with one more door."
else:
print "Please choose left or right."
In the if statement, I want to send the user back to choiceOne's raw_input(). In the elif statement, I want to give the user the option to either proceed through the next door, or return to the first room to see what secrets the other door may hold. Is there any way to do this? I don't care if the way is complicated or whatever, I just want to get this working.
Are you looking for a while loop?
I think that this website explains it very well: http://www.tutorialspoint.com/python/python_while_loop.htm
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
→
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
Use a while loop:
while True:
print "You are in a room with two doors to either side of you."
choice_one = raw_input("Which way will you go?").lower()
if choice_one == "r" or choice_one == "right":
print "You go through the right door and find yourself at a dead end."
continue # go back to choice_one
elif choice_one == "l" or choice_one == "left":
print "You go through the left door and find yourself in a room with one more door."
choice_two = raw_input("Enter 1 return the the first room or 2 to proceed to the next room")
if choice_two == "1":
# code go to first room
else:
# code go to next room
else:
print "Please choose left or right."
You need to use == for a comparison check, = is for assignment.
To break the loop you could add a print outside the loop print "Enter e to quit the game":
Then in your code add:
elif choice_one == "e":
print "Goodbye"
break
After the initial question of how much do you take, it works fine. If you type 0 you die, 5 million it says nice take. After it says nice take, it exits the program and forgets the rest of the code.
How do I get python to load the next part of the code and run it.
from sys import exit
def bank_vault():
print "This room is full of money up to 5 million dollars. How much do you take?"
choice = raw_input("> ")
if "0" in choice:
dead("You are robbing a bank and took nothing... The cops shot you in the face.")
how_much = int(choice)
if how_much < 5000000:
print "Nice take, now you have to escape!"
escape_route()
def escape_route():
print "There are cops blocking the front door."
print "There are cops blocking the back door."
print "There is no way to get out of there."
print "You see a small opening on the ceiling."
print "Type ceiling to go through it."
print "Or type stay to try your luck."
escaped_cops = False
while True:
choice = raw_input("> ")
if choice == "stay":
dead("Your bank robbing friends left your stupid ass and the cops shot you in the face. Idiot move dipshit.")
elif choice == "ceiling" and not escaped_cops:
print "You escaped! Now wash that money and don't go to prison."
escaped_cops = True
def dead(why):
print why, ""
exit(0)
bank_vault()
Cool game. I love games and would like to try to improve your code. Code below works on Python 3. It should work on Python 2:
from sys import exit
try: input = raw_input # To make it work both in Python 2 and 3
except NameError: pass
def bank_vault():
print("This room is full of money up to 5 million dollars. How much do you take?")
how_much = int(input("> ")) # Why not eliminate choice variable here?
if how_much == 0:
dead("You are robbing a bank and took nothing... The cops shot you in the face.")
elif how_much < 5000000: # Changed to else condition
print("Nice take, now you have to escape!")
else: # Added a check
dead("There isn't that much!")
def escape_route():
print("There are cops blocking the front door.")
print("There are cops blocking the back door.")
print("There is no way to get out of there.")
print("You see a small opening on the ceiling.")
print("Type ceiling to go through it.")
print("Or type stay to try your luck.")
escaped_cops = False
while not escaped_cops:
choice = input("> ")
if choice == "stay":
dead("Your bank robbing friends left your stupid ass and the cops shot you in the face. Idiot move dipshit.")
elif choice == "ceiling":
print("You escaped! Now wash that money and don't go to prison.")
escaped_cops = True
def dead(why):
print(why)
exit(0)
bank_vault()
escape_route()
You have to call the function escape_route rather than exit.
Also, when checking for choice you call dead no matter what.
In reply to your comment:
You need to check if it's 0 then call dead, if it's not 0 don't bother with the else, go directly to the if how_much < 5000000 and call escape_route
You need to try and convert the input to an int if it isn't 0!
And what happens if they take more than 5 mil?
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
def Game():
# Story Background
print "You decide to take a walk outside one night when you come accross a corn field."
print "You notice an omnious sound coming from the other side of the maze."
Enter = raw_input("Do you enter? (yes or no)")
if Enter == "Yes" or "yes":
print "You walk into the maze and the corn is so thick together you cant push through"
print "so you walk down the isle surrounded by corn and you come to an intersection."
turn = raw_input("Which way do you go? (Left, Right, Forward, Leave)")
if turn == "Left" or "left":
print "After you turn left you come accross a dead end and you are forced to turn around."
print "You return to the intersection."
turn2 = raw_input("Which way do you go? (Left, Forward, Leave)")
if turn2 == "Forward" or "forward":
print "you walk on deeper into the maze when you come to a left turn"
print "you turn left and come accross a crossroad."
turn3 = raw_input("Which way do you go? (Left, Right, Leave)")
if turn3 == "Right" or "right":
print "You come to a dead end and are forced to turn around"
turn4 = raw_input("Which way do you go? (Forward, Leave)")
if turn4 == "Forward" or "forward":
print "You walk to a hole in the ground stopping you from moving any further"
print "the hole seems to be filled with snakes so you cant go through it."
print "you are forced to leave the maze."
elif turn4 == "leave" or "Leave":
print "you leave the maze and return home."
else:
print "you walk into a wall and go into an irreversable coma"
elif turn3 == "Left" or "left":
print "You walk to a hole in the ground stopping you from moving any further"
print "the hole seems to be filled with snakes so you cant go through it."
print "you are forced to leave the maze."
print "you leave the maze and return home."
else:
print "you walk into a wall and go into an irreversable coma"
elif turn2 == "Left" or "left":
print "you turn Left into the maze when you come by a strange man laying on the ground."
man == raw_input("What do you do? (Help, keep going)")
if man == "Help" or "help":
print "you help the man up and he knocks you out cold"
print "you wake back up in your bed at home"
elif man == "keep going" or "Keep going":
print "You leave the man behing after stealing his wallet."
print "YOU HAVE REACHED THE END OF THE MAZE"
print "You realize the noise was the sound of a old farmer milking a cow."
print "The farmer nags at you for coming on private property."
else:
print "you walk into a wall and go into an irreversable coma"
elif turn2 == "leave" or "Leave":
print "you leave the maze and return home."
else:
print "you walk into a wall and go into an irreversable coma"
elif turn == "Forward" or "forward":
print "you move forward into the maze when you come by a strange man laying on the ground."
man == raw_input("What do you do? (Help, keep going)")
if man == "Help" or "help":
print "you help the man up and he knocks you out cold"
print "you wake back up in your bed at home"
elif man == "keep going" or "Keep going":
print "You leave the man behing after stealing his wallet."
print "YOU HAVE REACHED THE END OF THE MAZE"
print "You realize the noise was the sound of a old farmer milking a cow."
print "The farmer nags at you for coming on private property."
elif turn == "leave" or "Leave":
print "you leave the maze and return home."
else:
print "you walk into a wall and go into an irreversable coma"
elif turn == "Right" or "right":
print "After you turn right you come into a left turn only path."
print "You turn left and you come to a crossroad."
turn = raw_input("Which way do you go? (Left, Right, Leave)")
if turn == "Right" or "right":
print "You come to a dead end and are forced to turn around"
turn = raw_input("Which way do you go? (Forward, Leave)")
if turn == "Forward" or "forward":
print "You walk to a hole in the ground stopping you from moving any further"
print "the hole seems to be filled with snakes so you cant go through it."
print "you are forced to leave the maze."
else:
print "you walk into a wall and go into an irreversable coma"
elif turn == "Forward" or "forward":
print "You walk to a hole in the ground stopping you from moving any further"
print "the hole seems to be filled with snakes so you cant go through it."
print "you are forced to leave the maze."
else:
print "you walk into a wall and go into an irreversable coma"
elif turn == "Leave" or "leave":
print "you leave the maze and return home."
else:
print "you walk into a wall and go into an irreversable coma"
elif Enter == "No" or "no":
print "You walk on into the depths of the night and are robbed by a couple street thugs."
else:
print "you walk into a wall and go into an irreversable coma"
def main():
Game()
main()
when i use this program, no matter what i enter into the python shell, it says the same thing over and over again.. it wont take the raw_input statements into context and put them into the if statements
if Enter == "Yes" or "yes":
This is not how or works. This is interpreted as if (Enter == "Yes") or "yes":. In python, non-empty strings are always true, so all of the if statements like that will be true. I would suggest something like
if Enter.lower() == "yes":
which takes care of all of the upper/lower case combinations.
Your syntax is wrong here:
if Enter == "Yes" or "yes":
This condition will always be true. Enter == "Yes" is first evaluated. If boolean representation is False, the boolean representation of "yes" will be considered. bool("yes") is always True.
Consider doing something like:
if Enter in ('Yes', 'yes'):
Or:
if Enter.lower() == 'yes':