I am learning how to make a text typed game in python. I could not get it to work. eventhough there is a water in my list (bag) it would still end the game eventhough i have it. Please help me
...
bag = [ ]
sword = ("sword")
water_bucket = ("water")
dead = False
ready = input("are you ready? ")
while dead == False:
print("this is whats inside your bag ")
print(bag)
if ready == "yes":
print("let's start our journey ")
print(
"It was a beautiful morning, you woke up in a dungeon, your quest is to find a dragon and slay his head off")
while dead == False:
if dead == True:
break
else:
first = input("Choose a path front/back/left/right")
if first == "front":
if bag == "water":
print(" You got safe because of the water bucket")
else:
dead = True
print(" You died in a hot lava")
elif first == "back":
ask2 = input("There is a sword, do you want to take it?")
if ask2 == "yes":
bag.append(sword)
print("You got a sword")
elif ask2 == "no":
print("you did not take it and went back to start")
else:
print("please answer with yes or no")
elif first == "left":
if bag == "sword":
print("You fought a dragon and win")
elif bag != "sword":
print("You fought a dragon but lost because you do not have a weapon")
dead = True
elif first == "right":
ask3 = input("Water Buckets! might be helpful, take it? ")
if ask3 == "yes":
bag.append(water_bucket)
print("You got a water bucket")
print(bag)
elif ask3 == "no":
print("you did not take it and went back to start")
else:
print("please answer with yes or no")
else:
print("not a path")
else:
print("See you next time, A journey awaits")
...
It is a text based im learning right now
Related
I need to include a decrement life counter that has 5 lives. I need to use a while loop and once the player loses a life it needs to send them back to the choice between going left and right in the code. I am new to python so I am not very familiar with it, any help is appreciated.
answer = input("Do you want to go on an adventure? (Yes/No) ")
if answer.lower().strip() == "yes":
x=5
while x > 0:
print("You have ",x,"lives left.")
if x > 0:
break
x-=1
if x == 0:
break
answer= input("You are lost in the forest and the path splits. Do you go left or right? (Left/Right) ").lower().strip()
if answer == "left":
answer = input("An evil witch tries to cast a spell on you, do you run or attack? (Run/Attack) ").lower().strip()
if answer == "attack":
print("She turned you into a green one-legged chicken, you lost!")
elif answer == "run":
print("Wise choice, you made it away safely.")
answer = input("You see a car and a plane. Which would you like to take? (Car/Plane) ").lower().strip()
if answer == "plane":
print("Unfortunately, there is no pilot. You are stuck!")
elif answer == "car":
print("You found your way home. Congrats, you won!")
elif answer != "plane" or answer != "car":
print("You spent too much time deciding...")
else:
print("You are frozen and can't talk for 100 years...")
elif answer == "right":
import random
num = random.randint(1, 3)
answer = input("Pick a number from 1 to 3: ")
if answer == str(num):
print("I'm also thinking about {} ".format(num))
print("You woke up from this dream.")
elif answer != num:
print("You fall into deep sand and get swallowed up. You lost!")
else:
print("You can't run away...")
else:
print("That's too bad!")
You should try to add comments to your code, it will help you and others as well.
I think for getting user answer, you should use a different variable. It will make things easier.
I removed the following code, it didn't make any sense to me.
while x > 0:
print("You have ",x,"lives left.")
if x > 0:
break
x-=1
if x == 0:
break
--
This is the code, which works:
# Try to write imported modules at the top, it's a good practice.
import random
# Start the game
answer_start = input("Do you want to go on an adventure? (Yes/No) ")
# user chooses to play
if answer_start.lower().strip() == "yes":
lives=5
# function for displaying the lives
def display_lives():
print("You have ",lives,"lives")
#display lives
display_lives()
# As long lives are more than 0, this will keep going.
while lives>0:
#First choice
answer1= input("You are lost in the forest and the path splits. Do you go left or right? (Left/Right) ").lower().strip()
#User chooses left
if answer1 == "left":
answer2 = input("An evil witch tries to cast a spell on you, do you run or attack? (Run/Attack) ").lower().strip()
if answer2 == "attack":
print("She turned you into a green one-legged chicken, you lost!")
lives=lives-1
display_lives()
# User is running away
elif answer2 == "run":
print("Wise choice, you made it away safely.")
answer3 = input("You see a car and a plane. Which would you like to take? (Car/Plane) ").lower().strip()
if answer3 == "plane":
print("Unfortunately, there is no pilot. You are stuck!")
elif answer3 == "car":
print("You found your way home. Congrats, you won!")
elif answer3 != "plane" or answer3 != "car":
print("You spent too much time deciding...")
else:
print("You are frozen and can't talk for 100 years...")
elif answer1 == "right":
num = random.randint(1, 3)
answer4 = input("Pick a number from 1 to 3: ")
if answer4 == str(num):
print("I'm also thinking about {} ".format(num))
print("You woke up from this dream.")
elif answer4 != num:
print("You fall into deep sand and get swallowed up. You lost!")
lives=lives-1
else:
print("You can't run away...")
#Player chose not to play or player out of lives.
else:
print("That's too bad!")
I'm trying to catch an invalid input by the user in this function when the user runs the program. The idea is to use a try,exception block with a while loop to ensure that the code is continuously run until a valid input is made by the user, which is 1-5.
def door_one():
print("This door has many secrets let's explore it")
print("\nMake a choice to discover something")
print("1 2 3 4 5")
while True:
explore = input(" > ")
if explore not in ("1","2","3","4","5"):
raise Exception ("Invalid input")
if explore == "1":
print("You fought a bear and died")
elif explore == "2" or explore == "3":
print("You become superman")
elif explore == "4":
print(f"Dance to save your life or a bear eats you")
suffer("HAHAHAHAHAHAHAHA!!!!!!")
elif explore == "5":
a_file = input("Please input a file name > ")
we_file(a_file)
suffer("HAHAHAHAHAHAHAHA!!!!!!")
I would advise against using exceptions for controlling flows.
Instead, I would keep iterating until the value is correct and use a return statement to indicate I'm done.
def door_one():
print("This door has many secrets let's explore it")
print("\nMake a choice to discover something")
print("1 2 3 4 5")
while True:
explore = input(" > ")
if explore not in ("1","2","3","4","5"):
continue
if explore == "1":
print("You fought a bear and died")
elif explore == "2" or explore == "3":
print("You become superman")
elif explore == "4":
print(f"Dance to save your life or a bear eats you")
suffer("HAHAHAHAHAHAHAHA!!!!!!")
elif explore == "5":
a_file = input("Please input a file name > ")
we_file(a_file)
suffer("HAHAHAHAHAHAHAHA!!!!!!")
return
```import random
from random import randint
pc = randint(1, 3)
playerinput = input("1 = Rock, 2 = Paper, 3 = Scissors")
def start():
pc = randint(1, 3)
if playerinput == 1:
if pc == 2:
print("You lose!")
elif pc == 1:
print("You draw!")
else:
print("You win!")
elif playerinput == 2:
if pc == 2:
print("You draw!")
elif pc == 3:
print ("You lose!")
else:
print("You win!")
else:
if pc == 3:
print("You draw!")
elif pc == 2:
print("You win!")
else:
print("You lose!")
again = input("Would you like to play again? Type 'YES' if so")
if again == "YES" or "yes" or "Yes" or "yEs" or "yeS" or "YEs" or "YeS":
start()```
It prints the rock paper or scissors, then it just goes would you like to play again. if you say yes, it then prints whether you won, lost or tied. what's wrong?
You call the Player-input only once, so once the Player made on decision calling start() will only generate a new random int. From what I understand you want to change the code into something like this, asking the player for input each time start() is called:
(Note that the pc before the definition is not needed aswell, since you reset it in start())
import random
from random import randint
def start():
pc = randint(1, 3)
playerinput = input("1 = Rock, 2 = Paper, 3 = Scissors")
if playerinput == 1:
if pc == 2:
print("You lose!")
elif pc == 1:
print("You draw!")
else:
print("You win!")
elif playerinput == 2:
if pc == 2:
print("You draw!")
elif pc == 3:
print ("You lose!")
else:
print("You win!")
else:
if pc == 3:
print("You draw!")
elif pc == 2:
print("You win!")
else:
print("You lose!")
start()
while True:
again = input("Would you like to play again? Type 'YES' if so")
if again == "YES" or "yes" or "Yes" or "yEs" or "yeS" or "YEs" or "YeS":
start()
else:
break
EDIT: As stated in the comment to your question by a different user, you shuold change the if to just if again.lower() = "yes" to be more clean. Alsoimport randomis not necessary if you callfrom random import randint` afterwards.
That's because 'randint' randomly initialize a number from 1-3 whenever invoked.
randint(1, 3)
So, whichever number the user enters, the function reinitialize the number and prints:
either "You win!", "You lose!", or "You draw!".
You probably want to read input inside start.
Also, your if statement will always be True because
if "yes":
will pass.
In any case you want to do something like again.lower() == 'yes'
You forgot to call your function after defined it.
You need to add start() before again.
Also if you want to play everytime the user said yes you need to had a loop
import random
from random import randint
pc = randint(1, 3)
playerinput = input("1 = Rock, 2 = Paper, 3 = Scissors")
def start():
pc = randint(1, 3)
if playerinput == 1:
if pc == 2:
print("You lose!")
elif pc == 1:
print("You draw!")
else:
print("You win!")
elif playerinput == 2:
if pc == 2:
print("You draw!")
elif pc == 3:
print ("You lose!")
else:
print("You win!")
else:
if pc == 3:
print("You draw!")
elif pc == 2:
print("You win!")
else:
print("You lose!")
start()
while True:
again = input("Would you like to play again? Type 'YES' if so")
if again == "YES" or "yes" or "Yes" or "yEs" or "yeS" or "YEs" or "YeS":
start()
else:
break;
Consider adding the first input to the function start, remove the first pc = randint and then call the function below its definition.
I was writing a code in a programming book for beginners.
This is what it looks like. (I HAVE TO EXTEND THIS POST BECAUSE THIS WEBSITE IS SO FINICKY ABOUT QUESTION POSTS.)
import random
print("You are in a dark room in a mysterious castle.")
print("In front of you are four doors. You must choose one.")
playerChoice = input("Choose 1, 2, 3, or 4...")
if playerChoice == "1":
print("You found a room full of tresure. YOU'RE RICH!!!")
print("GAME OVER, YOU WIN!")
elif playerChoice == "2":
print("The door opens and an angry ogre hits you with his club.")
print("GAME OVER, YOU DIED!")
elif playerChoice == "3":
print("You encounter a sleeping dragon.")
print("You can do either:")
print("1) Try to steal some of the dragon's gold")
print("2) Sneak around the dragon to the exit")
dragonChoice = input("type 1 or 2...")
if dragonChoice == "1":
print("The dragon wakes up and eats you. You are delicious.")
print("GAME OVER, YOU WERE EATEN ALIVE.")
elif dragonChoice == "2":
print("You sneak around the dragon and escape the castle, blinking in the sunshine.")
print("GAME OVER, YOU ESCAPED THE CASTLE.")
else:
print("Sorry, you didn't enter 1 or 2.")
elif playerChoice == "4":
print("You enter a room with a sphinx.")
print("It asks you to guess what number it is thinking of, betwwen 1 to 10.")
number = int(input("What number do you choose?")
if number == random.randint (1, 10)
print("The sphinx hisses in dissapointment. You guessed correctly.")
print("It must let you go free.")
print("GAME OVER, YOU WIN.")
else:
print("The sphinx tells you that your guess is incorrect.")
print("You are now it's prisoner forever.")
print("GAME OVER, YOU LOSE.")
else:
print("sorry, you didn't enter 1, 2, 3, or 4...")
print("YOU TURN BACK AND LEAVE (YOU COWARD)")
Here are two of your problems:
number = int(input("What number do you choose?")
if number == random.randint (1, 10)
The cast to int is missing a closing parenthesis and the if statement is missing a colon.
The last problem has to do with the double else statement at the end. Un-indent the last one, assuming that is what you wanted.
Fixed:
import random
print("You are in a dark room in a mysterious castle.")
print("In front of you are four doors. You must choose one.")
playerChoice = input("Choose 1, 2, 3, or 4...")
if playerChoice == "1":
print("You found a room full of tresure. YOU'RE RICH!!!")
print("GAME OVER, YOU WIN!")
elif playerChoice == "2":
print("The door opens and an angry ogre hits you with his club.")
print("GAME OVER, YOU DIED!")
elif playerChoice == "3":
print("You encounter a sleeping dragon.")
print("You can do either:")
print("1) Try to steal some of the dragon's gold")
print("2) Sneak around the dragon to the exit")
dragonChoice = input("type 1 or 2...")
if dragonChoice == "1":
print("The dragon wakes up and eats you. You are delicious.")
print("GAME OVER, YOU WERE EATEN ALIVE.")
elif dragonChoice == "2":
print(
"You sneak around the dragon and escape the castle, blinking in the sunshine.")
print("GAME OVER, YOU ESCAPED THE CASTLE.")
else:
print("Sorry, you didn't enter 1 or 2.")
elif playerChoice == "4":
print("You enter a room with a sphinx.")
print("It asks you to guess what number it is thinking of, betwwen 1 to 10.")
number = int(input("What number do you choose?"))
if number == random.randint(1, 10):
print("The sphinx hisses in dissapointment. You guessed correctly.")
print("It must let you go free.")
print("GAME OVER, YOU WIN.")
else:
print("The sphinx tells you that your guess is incorrect.")
print("You are now it's prisoner forever.")
print("GAME OVER, YOU LOSE.")
else:
print("sorry, you didn't enter 1, 2, 3, or 4...")
print("YOU TURN BACK AND LEAVE (YOU COWARD)")
Python is a whitespace delimited language, which means you need to pay special attention to indentation. Your indentation is inconsistent which will inevitably lead to issues.
Other than that, you did not specify WHAT your error actually is. Add the syntax error information to your post.
You just had some problems with spacing and forgot ":" in line 30
import random
print("You are in a dark room in a mysterious castle.")
print("In front of you are four doors. You must choose one.")
playerChoice = input("Choose 1, 2, 3, or 4...")
if playerChoice == "1":
print("You found a room full of tresure. YOU'RE RICH!!!")
print("GAME OVER, YOU WIN!")
elif playerChoice == "2":
print("The door opens and an angry ogre hits you with his club.")
print("GAME OVER, YOU DIED!")
elif playerChoice == "3":
print("You encounter a sleeping dragon.")
print("You can do either:")
print("1) Try to steal some of the dragon's gold")
print("2) Sneak around the dragon to the exit")
dragonChoice = input("type 1 or 2...")
if dragonChoice == "1":
print("The dragon wakes up and eats you. You are delicious.")
print("GAME OVER, YOU WERE EATEN ALIVE.")
elif dragonChoice == "2":
print("You sneak around the dragon and escape the castle, blinking in the sunshine.")
print("GAME OVER, YOU ESCAPED THE CASTLE.")
else:
print("Sorry, you didn't enter 1 or 2.")
elif playerChoice == "4":
print("You enter a room with a sphinx.")
print("It asks you to guess what number it is thinking of, betwwen 1 to 10.")
number = int(input("What number do you choose?"))
if number == random.randint (1, 10):
print("The sphinx hisses in dissapointment. You guessed correctly.")
print("It must let you go free.")
print("GAME OVER, YOU WIN.")
else:
print("The sphinx tells you that your guess is incorrect.")
print("You are now it's prisoner forever.")
print("GAME OVER, YOU LOSE.")
else:
print("sorry, you didn't enter 1, 2, 3, or 4...")
print("YOU TURN BACK AND LEAVE (YOU COWARD)")
I'm working on a text-based RPG, but I've found numerous problems, like:
being unable to go anywhere after entering the shop;
I cannot access the "tavern" for some reason; and
the computer just says "buy is not defined in crossbow".
Code:
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.")
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")
The first time you ask the user where to go on line 111, what happens if they enter something besides "shop"? then the if choice == "shop": condition on line 119 will fail, and buy = input("...") will never execute. At that point, buy doesn't exist, so when the next conditional executes, it crashes because it can't evaluate if buy == "crossbow". buy has no value, so you can't compare it to anything.
You need to indent all of your shop logic so that it lies inside the if choice == "shop" block.
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")
#...etc
if buy == "spell":
print("this costs 35 gold")
And the same problem is present for your tavern code. Even if you don't go to the tavern, you check for tavernChoice. That needs to be indented as well.
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.")
At this point, your program will end, but I'm guessing you want to continue to be able to explore areas. You could put everything in a while loop, starting with the first input command.
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: ")
if choice == "shop":
print("Welcome to the shop!")
#...etc
elif choice == "tavern":
print("You enter the tavern...")
#...etc
elif choice == "forest":
print("You enter the forest...")
#etc
else:
print("Not acepted")
print("What do you wish to do?")
print("please input shop, tavern, forest.")
This is also a little cleaner than your current method, since you only have to ask the user where they're going once, instead of three times on lines 112, 165, and 170.
Building on Kevin's answer, here is a version with redundancy squeezed out, so you can add a new place just by adding a new def go_xyz(): ... near the top.
def go_shop():
print("Welcome to the shop!")
#...etc
def go_tavern():
print("You enter the tavern...")
#...etc
def go_forest():
print("You enter the forest...")
#etc
places = {name[3:]:globals()[name] for name in globals() if name.startswith('go_')}
placenames = ', '.join(places)
inventory = ['book']
retry = False
while True:
if not retry:
print("Here is your inventory: ", inventory)
else:
print("I do not know that place")
print("Where do you wish to go?")
print("Possible places: ", placenames, '.')
choice = input("? ")
try:
places[choice]()
retry = False
except KeyError:
retry = True