User input comparison isn't working - python

When the program goes to level one, and the game begins, I input the correct answer, but it does not work. The answer to the first quote is "death". The if else statement is supposed to acquire the answer of the user, and, if it is correct, display a message and move on to the next level. However, it does not. It displays another message telling me I lost.
I don't understand what is going on, especially since the if else statement picks up whether or not the user wants to view the rules.
Just to be safe, I am going to write one last clarification in a more straightforward form.
When I input the correct answer on level one, and I know for a fact it is the correct answer, it does not display the congrats_message, but it displays the loss_message.
welcome_message = "Hello! Welcome to Quote Game by Chandler Morell!"
version = "0.0.1"
congrats_message = "Congratulations! You passed level one!"
loss_message = "Sorry. You did not succeed. One life has been lost."
win_game_message = "Congratulations! You won the game!"
lost_game_message = "You made it to the end, but you did not win. Give it another go!"
lives = 3
def game_won():
print("")
print(win_game_message)
def game_lost():
print("")
print(lost_game_message)
def update_lives():
global lives
lives = lives - 1
if lives is 0:
print("You have ran out of lives. Game over.")
game_lost()
exit(0)
def view_rules():
rules = ["1. Do not look up quotes online.", "2. You have three lives.",
"3. You will have three words to choose from.", "4. Type the WORD not the NUMBER"]
print("")
for i in rules:
print(i)
def ask_view_rules():
rules_answer = input("Would you like to view the rules? (y/n): ")
if rules_answer is "y":
view_rules()
else:
print("")
print("Okay, let's begin!")
def level_one():
print("Lives: ", lives)
print("We will start with an easy quote. Fill in the blank.")
print("")
choices = ["1. death", "2. torture", "3. nothing"]
for i in choices:
print(i)
print("")
choice = input("Give me liberty or give me _____! - Patrick Henry ")
if choice is "death":
print("")
print(congrats_message)
print("")
level_two()
else:
print("")
print(loss_message)
print("")
update_lives()
level_two()
def level_two():
print("-----------------------")
print("")
print("Lives: ", lives)
print("Welcome to level two!")
print("")
choices = ["1. stupidity", "2. wisdom", "3. nobody"]
for i in choices:
print(i)
print("")
choice = input("Knowledge speaks, but ______ listens. - Jimi Hendrix ")
if choice is "wisdom":
print("")
print(congrats_message)
print("")
level_three()
else:
print("")
print(loss_message)
print("")
update_lives()
level_three()
def level_three():
print("-----------------------")
print("")
print("Lives: ", lives)
print("")
print("Wow. I am impressed!")
print("")
print(welcome_message)
print("Version: " + version)
ask_view_rules()
print("")
print("We will now begin the game!")
print("")
level_one()

As cricket_007 pointed out you need to use == instead of is in your code. This is because is returns True if both variables point to the same object whereas == returns True if the value of both variables are equal. I would also suggest that you use a line break in your code \n as opposed to using print(“”).

Related

Why colorama make printing slower in python (Thonny)?

It's my RPG assignment for our school. I made an RPG program about an encounter with a Pirate and conversing with him with a guessing game. When I didn't use Colorama, the program runs normal but when using it, it slows down the program when running. I submitted the got 18 or 20 which is not bad, and I suspected it's how my program runs that's why I didn't get the perfect score.
I'm wondering if you guys can help me how to run the program faster when using Colorama? I just really wanted to learn how to solve this kind of issue.
import random
import time
import colorama
from colorama import Fore, Back, Style
talk_again = 'y'
while talk_again == 'y':
print("\nThere is a pirate coming down the road...")
time.sleep(2)
try:
user_option = int(input("\nWhat would you like to do? \n [1] To greet! \n [2] To play a game of chance \n [3] To walk on \n>>> "))
greetings= ["Hello stranger", "Hi there stranger!","Ahoy stranger!","Hey","*He stops, staring at you & didn't say anything*"]
inventory = ["Sword", "Shield","Dagger","Choker","Healing potion", "Red gem", "Red diamond","Sword", "Armour"]
leaving = ["Argghhh!!!", "Arrgh!Shut up!","Dammit! Arrgghh!!!"]
# lowercase items in inventory list, so we can compare wager input text
lowercase_inventory = [x.lower() for x in inventory]
def speak(text): #This is pirate conversation function colored in red
colorama.init(autoreset=True) # Automatically back to default color again
print(Fore.RED + '\t\t\t\t' + text)
def guess_my_number(): # the guessing number game
colorama.init(autoreset=True)
speak("Great! Let's play game of chance.")
time.sleep(1.5)
speak("I have a magic pen we can play for. What can you wager?")
time.sleep(1.5)
print("This is your inventory:" , lowercase_inventory)
wager = input(">>> ").lower()
# if wager item available in lowercased inventory
if wager.lower() in lowercase_inventory:
speak("That is acceptable!, Let's play the game of chance!")
time.sleep(1.5)
speak("I've thought of number between 1 to 100, you have 10 trys to guess it")
time.sleep(1.5)
speak("If you guess correctly, magic pen will be added to your inventor")
time.sleep(1.5)
speak("Otherwise you will lose " + wager + " from your inventory")
time.sleep(1.5)
speak("Make your guess:")
random_number = random.randint(1,100)
count = 10
main_game = True
# while loop will keep runing either guessed number matches random number or count number reaches 1
while main_game and count > 0:
try:
guess = int(input(">>> "))
except ValueError:
speak("Arrghh! I said guess numbers from 1 to 100 only!! Do you wanna play or not?")
else:
if count == 0:
speak("HA HA HA!! You lose!")
# count decreses by one every time.
lowercase_inventory.remove(wager)
print("Your current inventory:", lowercase_inventory)
break
if guess == random_number:
speak("Darn it!.. You won in " + str(11 - count)+ " guesses") #str(11 - count) means subtract the guesses from 11
lowercase_inventory.append('Magic pen')
print("The magic pen has been added in your inventory.\nYour inventory now: ", lowercase_inventory)
break
elif guess > random_number:
speak("Lower the number kid! Guess again!")
count-=1 # count decreses by one every time.
speak(str(count)+" "+ "chances left!!")
elif guess < random_number:
speak("Make it higher!Guess again!")
count-=1 # count decreses by one every time.
speak(str(count)+" "+ "chances left!!")
else:
speak("You don't have this item in your inventory, We can't play!")
except ValueError:
print("\nType 1, 2 and 3 only!")
else:
while True:
if user_option == 1:
print("\nType to greet the pirate:")
input(">>> ")
speak(random.choice(greetings))
elif user_option == 2:
guess_my_number()
elif user_option == 3:
leave_input = input("\nWhat would you like to say on leaving?:\n>>> ")
if leave_input == 'nothing':
speak("*He glances at you, then looks away after he walk passeed you, minding his own business*")
else:
speak(random.choice(leaving))
talk_again = input("\nPlay again?(y/n) " )
if talk_again == 'n':
print("\n Goodbye!")
break
user_option = int(input("\nWhat would you like to do? \n[1] to greet! \n[2] to play a game of chance \n[3] to walk on \n>>> "))

the input is not working in the second time

when an invalid answer (a number higher than 2) is given and is sent back to the intro(name) (see the else statement at the bottom) which is the introduction, the choise1 is auto completed and is redirected to crowbar()
def intro(name):#added the whole code
print( name + " you are in a back of a car hands tied, you can't remember anything apart the cheesy pizza you had for breakfast")
time.sleep(1)
print("you can see 2 men outside the car chilling out, they haven't seen that you have waken up")
time.sleep(1)
print("you figure out that your hands are not tied hard and manages to break free")
time.sleep(1)
print("and you see a piece of paper with your adress in it on the armrest in the middle of the front seats")
time.sleep(1)
print(" you see a crowbar under the back seat ")
time.sleep(1)
print("CHOOSE WISELY")
time.sleep(1)
print("""
1)grab the crowbar
2)check to see if the door was open""")
def car():
if choise1 == 1:
crowbar()
elif choise1 == 2:
door()
else:
print("that's not a valid answer")
intro(name)
choise1 = int(input("enter 1 or 2"))
car()
you can use function with parameter in this example (x )
def car(x):
if x == 1:
print("crowbar()")
elif x == 2:
print("door()")
else:
print("that's not a valid answer")
print("intro(name)")
choise1 = int(input("enter 1 or 2"))
car(choise1)

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

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

Python won't print anything past my def in my Text Adventure

#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

Categories