I'm trying to make a pick your own adventure game in python and I was using a while loop to make sure that you can only pick two answers. Everything works except when the if statement gets what it was looking for then, instead of calling the function, it just ends the while loop.
choice_1 = input("\n jungle or coast? ")
choice_1_lower = choice_1.lower()
def jungle_1():
print(" You head into the the unruly jungle to find cover and come across a small \n cave that looks to be empty.\n This would be a perfect spot to setup camp.\n\n In order to get to the cave you have to cross a river.")
def coast_1():
print(" You wander the coast, your skin still aching, looking for any sign of \n wreckage. \n\n it's been 3 hours, you don't find anything.")
while choice_1_lower != "jungle" and choice_1_lower != "coast":
if choice_1_lower == "jungle":
jungle_1()
elif choice_1_lower == "coast":
coast_1()
elif choice_1_lower != "jungle" and choice_1 != "coast":
print(f" This is not a choice. {choice_1}")
choice_1_lower = None
choice_1 = input("\n jungle or coast? ")
choice_1_lower = choice_1.lower()
I've been brainstorming and I don't have any idea how to keep the function of the while loop while also keeping the function of the if statement.
The issue with your code is, that when entering jungle or coast the while loop is not entered at all.
One option would be to run the while loop 'forever' and use the break statement once you want to leave the loop.
choice_1 = input("\n jungle or coast? ")
choice_1_lower = choice_1.lower()
def jungle_1():
print(" You head into the the unruly jungle to find cover and come across a small \n cave that looks to be empty.\n This would be a perfect spot to setup camp.\n\n In order to get to the cave you have to cross a river.")
def coast_1():
print(" You wander the coast, your skin still aching, looking for any sign of \n wreckage. \n\n it's been 3 hours, you don't find anything.")
while True:
if choice_1_lower == "jungle":
jungle_1()
break
elif choice_1_lower == "coast":
coast_1()
break
elif choice_1_lower != "jungle" and choice_1 != "coast":
print(f" This is not a choice. {choice_1}")
choice_1_lower = None
choice_1 = input("\n jungle or coast? ")
choice_1_lower = choice_1.lower()
Related
my text based game goes in a loop after going "right" and it won't stop unless you stop the process
heres the code in python:
def entrance():
import os
import sys
print ('hello please type your name in')
name = input('')
print ('hello' ,name,)
print('''
.___.
/) ,-^ ^-.
// / \ |WMWMWMW| |>>>>>>>>>>>>> | />>\ />>\ |>>>>>>>>>>>>>>>>>>>>>>:>
`-------| |--------------| \__/ \__/ |-------------------'^^
\\ \ /|\ /
\) \ \_/ /
| |
|+H+H+H+|
\ /
^-----^
''')
print("Welcome to Run Run Run" ,name,)
print("Your mission is to find the your way out of a abandonded hospital.")
#this game is text based where you have to escape without disturbing "it"
directions = ["left" ,"right" ,"back"]
print('You awaken in what looks like the reception of the hospital. You feel like something is watching you but you ignore it. there are cobwebs and everything is in ruins. there are two doors which one do you go through?')
userinput = " "
while userinput not in directions:
print('options: left/right/back')
userinput = input()
#used if and elif to get more accurate answers
if userinput == "right":
TheHall()
elif userinput == "left":
death1()
elif userinput == "back":
NoReturn()
else:
print('type a valid option')
def NoReturn():
print('the door is locked you cant get out')
entrance()
def TheHall():
print('Continuing through the door, you have come upon a beam in the hallway. Beyond the beam, the floor appears to turn into blood. If you choose to continue down the blood path,')
Continue()
def Continue():
directions = ["forward" ,"back"]
print('You have continued down the hall. It turns out blood isnt as big of a deal as the movies make it out to be. The trail leads you to a room. There is rickety wooden plank leading to the other side. At the foot of the plank there are 3 beautiful feathers. To your left there is, nothing.')
userinput = " "
while userinput not in directions:
print('options: forward/back')
if userinput == "forward":
bridge()
elif userinput == "back":
entrance()
i have no idea what do to. i tried indenting it but it didn't work instead it presented me with an indentation error
In the Continue funcion you don't take input, you can just change code to
def Continue():
directions = ["forward" ,"back"]
print('You have continued down the hall. It turns out blood isnt as big of a deal as the movies make it out to be. The trail leads you to a room. There is rickety wooden plank leading to the other side. At the foot of the plank there are 3 beautiful feathers. To your left there is, nothing.')
userinput = " "
while userinput not in directions:
print('options: forward/back')
userinput = input()
if userinput == "forward":
bridge()
elif userinput == "back":
entrance()
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I got this sample rpg text adventure game online and im trying to understand the codes so that i can use it as a reference to develop my own text adventure game in the future. However, i am currently facing the error "gold is not defined at line 121 and i suspect is cause by indentation error. Although this is the error im facing so far, i believed that are more mistakes in the codes which i am glad for anyone to point it out.Thanks!
# gold = int(100)
inventory = ["sword", "armor", "potion"]
print("Welcome hero")
name = input("What is your name: ")
print("Hello", name,)
# role playing program
#
# spend 30 points on strenght, health, wisdom, dexterity
# player can spend and take points from any attribute
classic = {"Warrior",
"Archer",
"Mage",
"Healer"}
print("Choose your race from", classic,)
classicChoice = input("What class do you choose: ")
print("You are now a", classicChoice,)
# library contains attribute and points
attributes = {"strenght": int("0"),
"health": "0",
"wisdom": "0",
"dexterity": "0"}
pool = int(30)
choice = None
print("The Making of a Hero !!!")
print(attributes)
print("\nYou have", pool, "points to spend.")
while choice != "0":
# list of choices
print(
"""
Options:
0 - End
1 - Add points to an attribute
2 - remove points from an attribute
3 - Show attributes
"""
)
choice = input("Choose option: ")
if choice == "0":
print("\nYour hero stats are:")
print(attributes)
elif choice == "1":
print("\nADD POINTS TO AN ATTRIBUTE")
print("You have", pool, "points to spend.")
print(
"""
Choose an attribute:
strenght
health
wisdom
dexterity
"""
)
at_choice = input("Your choice: ")
if at_choice.lower() in attributes:
points = int(input("How many points do you want to assign: "))
if points <= pool:
pool -= points
result = int(attributes[at_choice]) + points
attributes[at_choice] = result
print("\nPoints have been added.")
else:
print("\nYou do not have that many points to spend")
else:
print("\nThat attribute does not exist.")
elif choice == "2":
print("\nREMOVE POINTS FROM AN ATTRIBUTE")
print("You have", pool, "points to spend.")
print(
"""
Choose an attribute:
strenght
health
wisdom
dexterity
"""
)
at_choice = input("Your choice: ")
if at_choice.lower() in attributes:
points = int(input("How many points do you want to remove: "))
if points <= int(attributes[at_choice]):
pool += points
result = int(attributes[at_choice]) - points
attributes[at_choice] = result
print("\nPoints have been removed.")
else:
print("\nThere are not that many points in that attribute")
else:
print("\nThat attribute does not exist.")
elif choice == "3":
print("\n", attributes)
print("Pool: ", pool)
else:
print(choice, "is not a valid option.")
While True:
print("Here is your inventory: ", inventory)
print("What do you wish to do?")
print("please input shop, tavern, forest.")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
crossbow = int(50)
spell = int(35)
potion = int(35)
if choice == "shop":
print("Welcome to the shop!")
print("You have", gold,"gold")
buy = input("What would you like to buy? A crossbow, a spell or a potion: ")
if buy == "crossbow":
print("this costs 50 gold")
answer = input("Do you want it: ")
if answer == "yes":
print("Thank you for coming!")
inventory.append("crossbow")
gold = gold - crossbow
print("Your inventory is now:")
print(inventory)
print("Your gold store now is: ", gold)
if answer == "no":
print("Thank you for coming!")
if buy == "spell":
print("this costs 35 gold")
answear2 = input("Do you want it: ")
if answear2 == "yes":
print("Thank you for coming!")
inventory.append("spell")
gold = gold - spell
print("Your inventory is now:")
print(inventory)
if answear2 == "no":
print("Thank you for coming!")
if buy == "potion":
print("this costs 35 gold")
answear3 = input("Do you want it: ")
if answear3 == "yes":
print("Thank you for coming!")
inventory.append("spell")
gold = gold - potion
print("Your inventory is now:")
print(inventory)
if answear3 == "no":
print("Thank you for coming!")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
while choice != "shop" or "tavern" or "forest":
print("Not acepted")
print("What do you wish to do?")
print("please input shop, tavern, forest.")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
if choice == "teavern":
print("You enter the tavern and see a couple of drunken warriors singing, a landlord behind the bar and a dodgy figure sitting at the back of the tavern.")
tavernChoice = input("Would you like to talk to the 'drunken warriors', to the 'inn keeper', approach the 'dodgy figure' or 'exit'")
if tavernChoice == "drunken warriors":
print("You approach the warriors to greet them.")
print("They notice you as you get close and become weary of your presence.")
print("As you arrive at their table one of the warriors throughs a mug of ale at you.")
if dexterity >= 5:
print("You quickly dodge the mug and leave the warriors alone")
else:
print("You are caught off guard and take the mug to the face compleatly soaking you.")
print("The dodgy figure leaves the tavern")
From a quick glance at it. #gold = int(100) is commented out on line 1.
This causes a issue because it doesn't know what gold is. it isn't defined. remove the # before it.
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()
#Asks player for their name and whether they wish to enter or not
character_name = input(" Welcome to The Tenabris Manor, what is your
name?:")
print("")
print(" The towering gates stand before you to the large Manor, do you
enter?")
print("")
inp = ""
while inp != "enter" and inp != "leave":
inp = input(" enter enter or leave: ")
if inp != "enter" and inp != "leave":
print(" You must type enter or leave")
if inp == "enter":
print(" You push with all your might on the large gates, it swings open with
a loud clunk.")
if inp == "leave":
print("")
print(" You turn around and go back, probably for the best.")
print("")
print(" Your character", character_name, "turned back and never returned.")
input(" Press enter to exit")
SystemExit("")
def choose_room():
#key = False is so the person does not have the key until going upstairs
global key
key = False
while True:
print("")
print(" Bookshelfs line the walls, a staircase is to the left and a door
is straight ahead.")
print("")
print(" Type 'a' to: Go up the stairs")
print(" Type 'b' to: To go through the door")
print(" Type 'c' to: To check the bookshelfs")
ans = input("")
if ans=='a':
print(" You walk up the creaking stairs")
print(" At the top of the spiral staircase is a small observatory.")
print(" Looking around on some of stacks of books littering the room
you")
print(" find a small key!")
key = True
continue
elif ans=='b':
#The door detects whether the key is True or not/they have the key or not.
if key == True:
print(" You open the door with the small key.")
elif key == False:
print(" The door is locked, you will need a key to go through
it.")
continue
return
choose_room()
else:
print("The door is locked, you will need a key to go through
it.")
continue
return
choose_room()
else:
ans == 'c'
print(" You look through the thousands of books.")
print(" None of them interest you.")
continue
return
choose_room()
Excuse my terrible Coding, this is my first project and I am surprised it works in the first place.
Also this is my first post on stack overflow.
My problem is this code worked perfectly did everything I needed it to, but then when I went to add some more detail to it, I decided to do that later and deleted everything I "added" now the code doesn't run anything but the first part before def choose_room():
No error message appears when I run it, it just does the first part then ignores the bit at "def choose_room():" completely.
Well that's all I can think of to add that might help find the cause. Next time I will make a copy of the file before changing anything so this doesn't happen again.
If nobody can find what the problem is, I will just try to remake the program from scratch again.
In Python, indentation is part of the syntax, so if you have things improperly indented your code won't behave as you would expect it to.
Corrected indentation:
#Asks player for their name and whether they wish to enter or not
character_name = input(" Welcome to The Tenabris Manor, what is your name?:")
print("")
print(" The towering gates stand before you to the large Manor, do you enter?")
print("")
inp = ""
while inp != "enter" and inp != "leave":
inp = input(" enter enter or leave: ")
if inp != "enter" and inp != "leave":
print(" You must type enter or leave")
if inp == "enter":
print(" You push with all your might on the large gates, it swings open with a loud clunk.")
if inp == "leave":
print("")
print(" You turn around and go back, probably for the best.")
print("")
print(" Your character", character_name, "turned back and never returned.")
input(" Press enter to exit")
SystemExit("")
def choose_room():
#key = False is so the person does not have the key until going upstairs
global key
key = False
while True:
print("")
print(" Bookshelfs line the walls, a staircase is to the left and a door is straight ahead.")
print("")
print(" Type 'a' to: Go up the stairs")
print(" Type 'b' to: To go through the door")
print(" Type 'c' to: To check the bookshelfs")
ans = input("")
if ans=='a':
print(" You walk up the creaking stairs")
print(" At the top of the spiral staircase is a small observatory.")
print(" Looking around on some of stacks of books littering the room you")
print(" find a small key!")
key = True
continue
elif ans=='b':
#The door detects whether the key is True or not/they have the key or not.
if key == True:
print(" You open the door with the small key.")
elif key == False:
print(" The door is locked, you will need a key to go through it.")
continue
return
choose_room()
else:
print("The door is locked, you will need a key to go through it.")
continue
return
choose_room()
else:
ans == 'c'
print(" You look through the thousands of books.")
print(" None of them interest you.")
continue
return
choose_room()
You defined the function choose_room() but never used/called it. It would go something like this.
#...
if inp == "enter":
print(" You push with all your might on the large gates, it swings open with a loud clunk.")
choose_room()
#...
Make sure to define the function before calling it. Place the def choose_room():... on top of the script or before actually choose_room
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?