How to add input into a text based program - python

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

Related

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

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

Python Code keeps repeating the Input Value even when I try to "end" the code

Here is my code, if you play it, then you should see what's wrong. I am not for sure how to end the code once the player dies or wins. Play till the ending and look at the code so you can understand what may be the issue.
Thanks so much, here is the code:
def start ():
print ("Hello! Welcome to Prison Break!")
print (""""You are a very infamous spy working with a foreign government in the US. You are always successful and have never been caught...until now.""")
print ("You were captured by the FBI when you were walking down the street after a mission, and they jumped you.")
print ("You don't know what is happening!")
description_of_room()
def description_of_room ():
print ("You wake up in a prison cell. Everything seems very old, dust lies on the ground, untouched for years.")
print ("The room seems empty besides the cell bars, crumbling wall behind you, and a pile of rubble.")
room_1()
def room_1 ():
print("")
prompt_0()
def prompt_0 ():
prompt_0 = input("What do you do?.")
try:
if prompt_0 == "look":
print(" ")
description_of_room() # goes internally into room_1
if prompt_0 == "cell bars":
print("You examine the cell bars carefully.")
print("The bars are very old, a wrench could be able to rip them open")
room_1()
if prompt_0 == "rubble":
print("You closely examine the rubble. You see a metal rusty handle of something.")
print("You pull it easily out of the rubble, its a old wrench, maybe it could be used on the cell bars.")
options()
elif prompt_0 == "wall":
print("You examine the crumbling wall.")
print("It is extremely old, it seems someone has cut away at it, making it delicate, a hammer could easily take care of it.")
room_1()
else:
print("Please type in cell bars, wall, rubble, or look")
room_1()
except ValueError():
print("ARE YOU CRAZY? DON'T TYPE NUMBERS! YOU'LL CRASH MY GAME!")
print(" ")
room_1()
room_1()
options()
def options():
print()
prompt_1()
def prompt_1():
prompt_1 = input("Use wrench on bars or trade with Billy for a Hammer, who is next door.")
try:
if prompt_1 == "use wrench":
print("The wrench will be able to break open the cell bars.")
print("If you do it now you will be caught, you must wait till night.")
escape_2_mor()
if prompt_1 == "trade with billy":
print("Billy is the common trader in the prison, he will take pretty much anything.")
print("You give the rusty wrench to Billy and he gives you a decent small hammer, which can be used to smash the crumbly wall.")
failure()
elif prompt_1 == "Random":
print("RANDOM")
options()
else:
print("Type trade with billy or use on cell bars.")
options()
except ValueError():
print("NO NUMBERS!")
print(" ")
options()
def escape_2_mor():
print()
prompt_3()
def prompt_3():
prompt_3 = input("What do you do?")
try:
if prompt_3 == "wait":
print("You wait till night.")
escape_2_nih()
elif prompt_3 == "use wrench":
print("You were caught by the police, punishment is death.")
print("You died, Game Over!")
end()
else:
print("Type wait or use wrench")
escape_2_mor()
except ValueError():
print("I SAID NO NUMBERS")
print(" ")
escape_2_mor()
def escape_2_nih():
print()
prompt_4()
def prompt_4():
prompt_4 = input("It's midnight, you have the chance to use the wrench!")
try:
if prompt_4 == "use wrench":
print("You slowly break the old bars, the noise echoing throughout the halls.")
escape_2_nih_1()
elif prompt_4 == "wait":
print("You wait for no reason, it's morning again.")
escape_2_mor()
else:
print("Type use wrench or wait")
except ValueError:
print("Why do I even try...")
print(" ")
escape_2_nih()
def escape_2_nih_1():
print()
prompt_5()
def prompt_5():
prompt_5 = input("Your outside your cell bars, in a dark hallway, what do you do?")
try:
if prompt_5 == "crawl":
print("You get on your knees quietly, making sure no one can see you.")
print("You stick in the shadows and come across a guard.")
print("You hit him on the head with the wrench, luckily he is wearing a helmet, so he is just knocked out.")
escape_2_des
elif prompt_5 == "run":
print("You run quickly down the hallway, you see other cellmates sleeping.")
print("You almost reach the metal door at the end of the hallway, but a guard turns and sees you.")
print("He is so suprised that he fires his gun before you can attack him.")
print("You fall to the ground, everything goes dark, you died.")
end()
else:
print("Please type crawl or run")
escape_2_nih_1()
except ValueError:
print("Just stop")
escape_2_nih_1()
escape_2_des()
def escape_2_des():
print()
prompt_6()
def prompt_6():
prompt_6 = input("You press open the door and you see towering gates and a guard tower, what do you do?")
try:
if prompt_6 == "tower":
print("You see the tower, and slowly approach it. You reach the tower and see its made out of stone that can be easily climbed.")
print("You climb up the wall, and then reach the top. You can see that the tower is high enough to jump over the fence and escape.")
print("You take a huge leap and fall to the ground, you look behind you and see the fence and the prison.")
print("You have escaped the prison! You Win!")
end()
if prompt_6 == "fence":
print("You slowly approach the fence and put your hand on it to start climbing.")
print("You are quickly electrocuted by the electric fence, stopping your heart.")
print("You've lost!")
end()
else:
print("Type fence or tower")
escape_2_des()
except ValueError:
print("Your annoying")
escape_2_des()
def failure():
print()
prompt_7()
def prompt_7():
prompt_7 = input("You can now break open the crumbled wall")
try:
if prompt_7 == "break wall":
print("You hammer away at the wall, which is breaking down easily.")
print("All the sudden a guard comes up from behind and stares down at you.")
print("Hello Officer! How are you doing today?")
print("Please come with me inmate.")
print("He pulls you by the shoulders and walks you down into a different cell, a more clean and sturdy cell.")
print("He pushes you in and locks the cell bars behind you, you have failed and will never get out.")
end()
if prompt_7 == "wait":
print("You wait for no reason, good job!")
failure()
else:
print("Type wait or break wall")
except ValueError:
print("Whatever")
failure()
end()
def end():
print("Congrats you have either won or failed the game. I hope you enjoyed!")
print(" ")
print("Ignore the statement underneath, the code is being an idiot")
start()
It would be a huge help if anyone could help, thank you. I am not for sure if it's the input that is the issue or what, but it keeps repeating. You can use pycharm if you have it because that is what works for me, if it does not work in any of the other programs you may use to run python then just try to please use Pycharm because I know it works.
Your end function doesn't actually stop the code execution. what you need to do is this
import sys
#your code
#your code
#your code
def end():
print("Congrats you have either won or failed the game. I hope you enjoyed!")
print(" ")
print("Ignore the statement underneath, the code is being an idiot")
sys.exit()

Still new to python. So confused right now. How do I make this program work?

So I'm making a little game to teach myself how python works, and it's been okay up to this point, but now I'm completely stuck. I'm sure the logic and formatting of the if and while statement are all wrong, so I'd be happy if people could point me in the right direction - again, REALLY new to programming in general. I'll paste the code, then explain what I'm trying to make it do:
import random
import time
print("Welcome to the Dojo!")
print("You have three opponents; they are ready...")
print("Are you?")
print("*To view the rules, type 'rules' ")
print("*To view commands, type 'commands' ")
print("*To begin, type 'start' ")
while True:
userInput = (input())
# Rules
if userInput == "rules":
print("The rules in this Dojo are simple. Kill your opponent! Fight to the death! Show no mercy!")
print("Each opponent gets progressively more difficult, whether it be in terms of health or damage.")
print("To attack, type 'attack'")
print("May the better (luckier) warrior win")
# Commands - to be added
elif userInput == "commands":
print("Commands will be added soon!")
# Start
elif userInput == "start":
damage = random.randint(1, 50)
userHealth = int(100)
opponentHealth = int(100)
print("Your first opponent is Larry Schmidt. Don't sweat it, he'll be a piece of cake.")
time.sleep(3)
print("The battle will begin in")
time.sleep(1)
print("5")
time.sleep(1)
print("4")
time.sleep(1)
print("3")
time.sleep(1)
print("2")
time.sleep(1)
print("1")
time.sleep(1)
print("Fight!")
if userInput == "attack":
int(userHealth - damage)
print("You did %(damage) to Larry!")
# Invalid response
else:
print("Enter a valid response, young grasshopper.")
if userInput == "start" is True:
continue
If you run the program for yourself, everything is okay until you reach the "5, 4, 3, 2, 1, Fight!" part. Then when you type "attack," it gives you "Enter a valid response, young grasshopper." I understand why this is happening, because "attack" doesn't fall under "rules", "commands", or "start". I just don't get how I'm supposed to format it so that after I enter "attack", it actually proceeds and outputs the damage done, etc. I apologize if this is hard to understand, but I think if you run it for yourself, you'll understand what I'm having problems with. Honestly, something tells me I've messed up the if and while statements up entirely, but hey, I'm learning and having fun :P.
Thanks for any help.
You aren't asking for more input. It's guaranteed that the userInput will still be "start" at that point.
Your code would benefit greatly from the use of functions. You could really organize the code better that way.
def intro():
print("Welcome to the Dojo!")
print("You have three opponents; they are ready...")
print("Are you?")
print("*To view the rules, type 'rules' ")
print("*To view commands, type 'commands' ")
print("*To begin, type 'start' ")
def get_user_input():
user_input = (input())
while user_input not in ['rules', 'commands', 'start']:
print("valid commands are rules, commands and start")
user_input = (input())
return user_input
intro()
returned_user_input = get_user_input()
There are a lot of ways to do these things, and you'll get better with time. Mainly note that user_input only gets updated when you do this:
user_input = (input())
Which in your code was only done once.
The code you have in the "start" branch of the if conditional will only run once, and userInput will still be "start" at that point. The solution, wrap it in a loop. Maybe something like this:
elif userInput == "start":
userHealth = 100
opponentHealth = 100
print("Your first opponent is Larry Schmidt. Don't sweat it, he'll be a piece of cake.")
time.sleep(3)
print("The battle will begin in")
time.sleep(1)
print("5")
time.sleep(1)
print("4")
time.sleep(1)
print("3")
time.sleep(1)
print("2")
time.sleep(1)
print("1")
time.sleep(1)
print("Fight!")
while opponentHealth > 0 and userHealth > 0:
userInput = input()
if userInput == "attack":
damage = random.randint(1, 50)
opponentHealth = opponentHealth - damage
print("You did %d to Larry!" % damage)
The while loop will loop until the opponent has been defeated or until the user is defeated, but at the moment, there's no damage done to the user. I'll leave that part to you.

Python programming, syntax error for game

#makes a varible called name to identify the players name
name=input("Hello person, Whats your name?")
#prints their name
print("Hello", name)
#console asks the player if they want to play the game, if choice is "yes" then continue, else say "ok bye bye" (at the bottom!!)
print("Do you want to hear a story?", name)
choice=input("Yes, No?")
if choice==("yes" or "yes " or "Yes" or "Yes "):
print("Ok", name,", listen up")
print("There was once an old, old house at the top of a hill Sooooo high it was above the clouds")
housename=input("What do you want to call the house?")
print("The old,",housename,"was once owned by an old lady. You decide to go up to the", housename, ",you encounter a ghost in your path. You see a varitety of weapons beside you, an axe, sword and a bow.")
#asks the player if they want an axe sword or bow
choice3=input("Do you choose the axe, sword or bow?")
#if the choice is "bow" then proceed with this code
if choice3==("bow" or "Bow" or "bow " or "Bow "):
print("You equip the shoddy Bow, The bow feels as if it could snap any second.")
#sets the enemyshealth as 10
enemyhealth=int(10)
#makes a while loop to keep the battle going instead of 1 time.
while enemyhealth >= 1:
print("Take a shot!")
bowattack=input("Type attack to fire an arrow!")
if bowattack==("attack"):
import random
#randomiser for damage generator
damage = ["1", "2", "3", "4"]
damage2 = int(random.choice(damage))
enemyhealth = enemyhealth - damage2
print("The ghost took some damage. Enemys health:", enemyhealth)
else:
print("Are you sure you typed shoot?")
#if the enemys health gets below 1 print you killed the ghost, reward system! **this is what im having trouble with!!**
if enemyhealth <= 1:
print("You killed the Ghost!!")
print("You vanquished the ghost, you now collect a new weapon!")
#confirms the reward, either gives the player a shiny bow or a double shot bow.
import random
reward = ["Shiny bow", "Doubleshot bow"]
#randomiser for either reward
reward2 =(random.choice(reward)
#prints what weapon the player got
#THIS IS THE PROBLEM, ON THIS LINE
print("You got a:", reward2)
#pointless easteregg :D
elif choice==("maybe"):
print("You found an easter egg, congrats. PS this does nothing")
#if the player typed anything other than yes say ok bye bye.
else:
print("Ok, bye bye", name)
I am fully aware that the code does not yet have the other 2 if statements for the axe or sword. What i'm having trouble with is the reward generator for killing the ghost. I think its an indention error; it says syntax error for the print line.
I know this is rather alot of code to take in but i'd really appreciate it if could help me fix this; if you see anything I could make a shortcut around that would also be helpful.
Im using python 3.4.2!
You're missing a closing parenthesis in the previous line:
reward2 =(random.choice(reward)
should be:
reward2 =(random.choice(reward))
Also, the line if choice==('yes' or 'yes ' or 'Yes' or 'Yes '): wont work.
Try this:
if choice.strip().lower() == 'yes':
# whatever
strip will remove whitespaces. lower will put the string in lowercase
The same happens with choice3

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