script auto looping after reaching a certain point in text based game - python

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()

Related

calling a function with an if statement and a while loop

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()

How do i make a command in python which can be used by the user throughout the python game?

The title might not help much, but it was the only way i could really explain it in a sum of a "sentence".
Here's my query:
I'm new to python, yes, new.
We are making this text adventure game in python. The character ("user") in the game should be able to see their "xp" in the replit console when the game asks "do you want to see your xp?". The user will reply yes, so it will show. How do i make it so that you can see your xp throughout the game and if a monster or something takes or increases your xp. How would it(the xp) be edited? Would it be using the .append command?
The same goes with the backpack in the code below. Would it be .append("object here")?
Here's my code so far
import time
#inventory/statistics
backpack = ("flashlight", "2 water bottles", "Am apple", "A blanket")
#the beginning, linked to the last code
name = input("Welcome to Medolxa adventurer! Please type your name, to begin this mysterious adventure: \n")
time.sleep(1)
print("Great, welcome to Medolxa",name,"!")
time.sleep(1)
#this is the second part of the game
def main():
print("Hint: Use these wisely, your HP will decrease any time if used insufficiently, your HP will be mentioned throughout the game,or maybe ")
time.sleep(1)
#the introduction to the game
def intro():
print("/ \ / \ ____ | | ____ ____ _____ ____ ")
print("\ \/\/ // __ \| | _/ ___\/ _ \ / \_/ __ ")
print(" \ /\ ___/| |_\ \__( <_> ) Y Y \ ___/ ")
print(" \__/\ / \___ >____/\___ >____/|__|_| /\___>")
print("Loading...")
time.sleep(2)
print("You leave the boat and head onto the wet land, the others follow just behind you")
time.sleep(1)
print("You seem to be in the middle of nowhere, the grass is wet")
time.sleep(1)
inventory = input("You have a backpack, would you like to see what is inside?: (y/n) \n")
if inventory == "n":
print("alrighty")
main()
elif inventory == "y":
print(backpack, "this is all you have right now!")
main()
#beginning (to make the code work, this is the main menu)
start = True
while start==True:
yes = "y"
no = "n"
game = input("This game is a horror, mysterious gane, would you like to continue?: (y/n) \n")
if game == yes:
print("Alrighty, let's go!")
start = False
intro()
elif game == no:
print("Game has ended, come back once you're ready!")
start = False
should i make a file and then do "file.append("object here")? for the backpack and for the xp i'd do file.append(12) etc and then do file.read?

How do i make my game link back to the start once user has made the wrong choice

im currently creating a text based adventure game, and i need to get the game to go back to the beginning once the user has died or chosen the wrong answer. i need it to ask the user if they wish to play again and then loop back to the beginning of the game.
anyone know how to do this, the help would be greatly appreciated.
this is the code -
#Python Text Adventure Game
#Created By Callum Fawcett
#Created On 20/07/19
#Version 0.1
# Setup
yes_no = ["yes", "no"]
directions = ["left", "right", "forward", "backward"]
# Introduction
name = input("What is your name, adventurer?\n")
print("Greetings, " + name + ". Let us go on a quest!")
print("You find yourself on the edge of a dark Jungle.")
print("Can you find your way through? and find the Hidden treasure at the end?\n")
# Start of game
response = ""
while response not in yes_no:
response = input("Would you like to step into the Jungle?\nyes/no\n")
if response == "yes":
print("You head into the Jungle. You hear crows cawwing in the distance.\n")
elif response == "no":
print("You are not ready for this quest. Goodbye, " + name + ".")
quit()
else:
print("I didn't understand that.\n")
# Second part of game
response = ""
while response not in directions:
print("To your left, you see a Tiger.")
print("To your right, there is more Jungle.")
print("There is a rock wall directly in front of you.")
print("Behind you is the Jungle exit.\n")
response = input("What direction do you move?\nleft/right/forward/backward\n")
if response == "left":
print("The Tiger eats you. Farewell, " + name + ".")
quit()
elif response == "right":
print("You head deeper into the Jungle.\n")
elif response == "forward":
print("You cannot scale the wall.\n")
response = ""
elif response == "backward":
print("You leave the Jungle. Goodbye, " + name + ".")
quit()
else:
print("I didn't understand that.\n")
# Third Part of game
response = ""
while response not in directions:
print("To your left, there is a waterfall.")
print("To your right, you see a run down house.")
print("Directly in front of you is a dark staircase.")
print("Behind you is the exit.\n")
response = input("What direction do you wish to take?\nleft/right/forward/backward\n")
if response == "left":
print("You look off the edge of the waterfall, taking the time to think about your choices.\n")
response = ""
elif response == "right":
print("The house is a trap, the doors and windows all shut behind you and youre trapped, Farewell, " + name + ".")
quit()
elif response == "forward":
print("You head down the strairs\n")
elif response == "backward":
print("You leave the Jungle. Goodbye, " + name + ".")
quit()
else:
print("I didn't understand that.\n")
# Fourth part of game
response = ""
while response not in directions:
print("You're now at the bottom of the staircase, it has a come to a fork")
print("To the right is a well lit path with a sign that reads 'Death to all who continue'.")
print("To the left is a dark and gloomy path with a sign that reads 'free passage to all those who continue'. ")
print("Directly in front of you is a a 50ft drop.")
print("Behind you is the exit.\n")
response = input("What direction do you wish to take?\nleft/right/forward/backward\n")
if response == "left":
print("You are attacked by forrst deamons. Goodebye," + name + ".")
quit()
elif response == "right":
print("You continue through the forrest.\n")
elif response == "forward":
print("You cant go down there youll die.\n")
response = ""
elif response == "backward":
print("You leave the Jungle. Goodebye" + name + ".")
quit()
else:
print("I Didn't understand that.\n")
#Fifth part of game
response = ""
while response not in directions:
print("You have continued through the dark forrest, and found yourself at a cross road.")
print("To your left is a beaten path with a man lying on the ground.")
print("To your right is a door.")
print("Straight ahead is a dark path that is over grown and full of brambles and thorns.")
print("behind you is the way you came and the way out.\n")
response = input("What direction do you wish to take?\nleft/right/forward/backward\n")
if response == "left":
print("You walk to help the man, but it was a trap and you are attacked and killed by savages. Goodbye, " + name + ".\n")
quit()
elif response == "right":
print("You go through the door, and it takes you to a mystical realm that you do not know, and now youre traped there. Goodbye, " + name + " Have fun.\n")
quit()
elif response == "forward":
print("You continue through the dark Jungle, getting deeper and deeper. Lets hope you're not lost ;)\n")
elif response == "backward":
print("You Leave the Jungle. Goodbye" + name + ".")
quit()
else:
print("I Didn't understand that")
#sixth part of the game.
response = ""
while response not in directions:
print("You have made it through the thorns and brambles, and have come to a T in the path.")
print("To your left is a bridge that doesnt look very stable and could break with the slightest bit of weight on it.")
print("To your right is a dark path with a metal bridge that looks sturdy and safe.")
print("Directly in front of you is a wall.")
print("Behind you is the way you came and the way out.\n")
response = input("What direction do you wish to take?\nleft/right/forward/backward\n")
if response == "left":
print("The bridge was actually very safe and you make your way over it, and continue on your quest\n")
elif response == "right":
print("The bridge wasnt stable and you have fallen to your death. Goodbye" + name + ".\n")
quit()
elif response == "forward":
print("You cannot scale the wall\n")
response = ""
elif response == "backward":
print("You leave the Jungle. Goodbye" + name + ".")
quit()
else:
print("I Didn't Understand That")
#Final Part of The Game
response = ""
while response not in directions:
print("You have come to the jungle temple, you make your way in through the door. Once inside you see three doors.")
print("The door on the left has a weird symbol above it, and what looks like blood coming out from under the door.")
print("The door on the right has no symbol above it, but does have two large lion statues by the door.")
print("The door straight in front of you has a crown symbol above it, but has two skelitons sat outside it.")
print("behind you is the way you came in and the way out.\n")
response = input("What direction do you wish to take?\nleft/right/forward/backward\n")
if response == "left":
print("You open the door and something drags you inside, for you to never be seen again. Goodbye" + name + ".\n")
quit()
elif response == "right":
print("You open the door and go inside, only to find 10 large lions who have not been fed in a very long time, they eat you. Goodbye" + name + ".\n")
quit()
elif response == "forward":
print("You open the door and walk down the strairs infront of you, as you get lower and lower you start to see all the gold and treasure that has been left.")
print("CONGRATULATIONS " + name + ", you found the Hidden jungle treasure, along with an exit back to the world.")
elif response == "backward":
print("You leave the temple and there are re risen soldiers ready to kill you. you die, Goodbye " + name + ".\n")
quit()
else:
print("I Didn't understant that")
put all your code inside a while loop and put continue to jump to the beginning of the loop
while True:
...
...
if response == "some wrong answer": continue
...
...
A possible solution: move all of your current code to a function, let's call it "gameplay",
and encapsulate it in a loop in the main function
def gameplay():
# Setup
yes_no = ["yes", "no"]
....
....
....
if __name__ == "__main__":
while True:
response = input("start a new game?y/n")
if response != "y":
break
print("Starting a new game")
gameplay()

How to add input into a text based program

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()

How do I move to different parts of code in this game/story

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?

Categories