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

#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

Related

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)

Python - Loop Escaping unexpectedly and not iterating over list as expected

import random
import time
def closest_num(GuessesLog, CompNum):
return GuessesLog[min(range(len(GuessesLog)), key=lambda g: abs(GuessesLog[g] - CompNum))]
GameModeActive = True
while GameModeActive:
Guesses = None
GuessesLog = []
while not isinstance(Guesses, int):
try:
Guesses = int(input("How many guesses do you have?: "))
except ValueError:
print("Please enter a whole number")
print(" ")
CompNum = random.randint(1,99)
print(CompNum)
Players = None
while not isinstance(Players, int):
try:
Players = int(input("How many players are there?: "))
except ValueError:
print("Please enter a whole number")
print(" ")
NumberOfPlayers = []
for i in range(Players):
NumberOfPlayers.append(i+1)
NumberOfGuesses = []
for i in range(Guesses):
NumberOfGuesses.append(i+1)
print(NumberOfGuesses)
print(NumberOfPlayers)
print(len(NumberOfGuesses))
print(len(NumberOfPlayers))
for Guess in NumberOfGuesses:
if Guess != len(NumberOfGuesses):
print("ITS ROUND {}! GET READY!".format(Guess))
print(" ")
PlayersForRound = NumberOfPlayers
for Player in PlayersForRound:
print("It is Player {}'s Turn >>>".format(Player))
print(PlayersForRound)
print(NumberOfPlayers)
PlayerEntry = None
while not isinstance(PlayerEntry, int):
try:
PlayerEntry = int(input("Enter guess number {}: ".format(Guess)))
print(" ")
except ValueError:
print("Please enter a whole number")
print("CALCULATING YOUR RESULT!")
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***")
if PlayerEntry == CompNum:
print("Congratulations player {}, you have successfully guessed the number on round {}!".format(Player, Guess))
print(" ")
NumberOfPlayers.pop(Player-1)
if len(NumberOfPlayers) == 1:
print("Only {} Player remains".format(len(NumberOfPlayers)))
PlayersForRound
elif len(NumberOfPlayers) > 1:
print("Only {} Players remain".format(len(NumberOfPlayers)))
continue
elif PlayerEntry < CompNum:
print("Your guess was too low!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
elif PlayerEntry > CompNum:
print("Your guess was too high!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
if Guess == len(NumberOfGuesses):
print("ITS ROUND {}! THIS IS THE LAST ROUND! GOOD LUCK!".format(Guess))
print(" ")
print(NumberOfGuesses)
print(NumberOfPlayers)
print(len(NumberOfGuesses))
print(len(NumberOfPlayers))
PlayersForRound = NumberOfPlayers
for Player in PlayersForRound:
print("It is Player {}'s Turn >>>".format(Player))
PlayerEntry = None
while not isinstance(PlayerEntry, int):
try:
PlayerEntry = int(input("Enter guess number {}: ".format(Guess)))
print(" ")
except ValueError:
print("Please enter a whole number")
print("CALCULATING YOUR RESULT!")
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***")
if PlayerEntry == CompNum:
print("Congratulations player {}, you have successfully guessed the number on round {}!".format(Player, Guess))
print(" ")
NumberOfPlayers.pop(Player-1)
if len(NumberOfPlayers) == 1:
print("Only {} Player remains".format(len(NumberOfPlayers)))
elif len(NumberOfPlayers) > 1:
print("Only {} Players remain".format(len(NumberOfPlayers)))
continue
elif PlayerEntry < CompNum:
print("Your guess was too low!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
elif PlayerEntry > CompNum:
print("Your guess was too high!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
print("The closest guess was ", closest_num(GuessesLog, CompNum))
print(" ")
while True:
Answer = input("Would you like to play again? Y/N: ")
if Answer.lower() not in ('y', 'n'):
print("Please enter either Y for Yes, or N for No.")
else:
break
if Answer == 'y':
GameActiveMode = True
elif Answer == 'n':
GameActiveMode = False
print("Thankyou for playing ;)")
break
holdCall = str(input("Holding the console, press enter to escape."))
In my above code, when there are multiple players and multiple guesses(Rounds) then it works fine unless someone successfully guesses the code. If the code is guessed the code deletes the correct record from the player list. But for some reason fails to iterate over the rest of the list or if the correct guess comes from the second user it skips the next player altogether and moves onto the next round.
I have absolutely no idea why. Anyone have any ideas? Thanks in advance.
For example, if you run this in console and then have 3 guesses with 3 users, on the first player you guess incorrectly. On the second you guess correctly, it skips player 3 and goes straight to round 2. Despite only remove player 2 from the list after a correct guess.
Or if you guess it correctly the first time around it skips to the 3rd player?
You are keeping track of players in the current round using a list of player numbers. So, if you start with three players, PlayersForRound will start as [1,2,3].
You then proceed to loop over this list to give each player their turn by using for Player in PlayersForRound. However, PlayersForRound and NumberOfPlayers are the exact same list (not a copy), so when you remove a player from one, it is removed from both.
Once a player guesses correctly, you remove them from the list you were looping over with NumberOfPlayers.pop(Player-1). For example if the second player guesses correctly, you remove their "index" from the list and the resulting list is now [1,3].
However, because Python is still looping over that same list, player 3 never gets their turn, because their "index" is now in the position where the "index" of player 2 was a moment ago.
You should not modify the list you're looping over, this will result in the weird behaviour you are seeing. If you want to modify that list, you could write a while loop that conditionally increases an index into the list and checks whether it exceeds the length of the list, but there are nicer patterns to follow to achieve the same result.
As for naming, please refer to https://www.python.org/dev/peps/pep-0008/ - specifically, your variables like PlayersForRound should be named players_for_round, but more importantly, you should name the variables so that they mean what they say. NumberOfPlayers suggests that it is an integer, containing the number of players, but instead it is a list of player numbers, etc.
The selected bits of your code below reproduce the problem, without all the fluff:
# this line isn't in your code, but it amounts to the same as entering '3'
Players = 3
NumberOfPlayers = []
for i in range(Players):
NumberOfPlayers.append(i+1)
PlayersForRound = NumberOfPlayers
for Player in PlayersForRound:
# this line is not in your code, but amounts to the second player guessing correctly:
if Player == 2:
NumberOfPlayers.pop(Player-1)
if Player == 3:
print('this never happens')
# this is why:
print(PlayersForRound, NumberOfPlayers)
When you pop the list, you intervene in the for loop. Here, you can play with this and see yourself.
players = 3
player_list = []
for p in range(players):
player_list.append(p + 1)
for player in player_list:
print(player)
if player == 2:
print("popped:",player_list.pop(player-1))
Output
1
2
popped: 2

How can I return my code to the start of the code?

I've been trying to return my code to the beginning after the player chooses 'yes' when asked to restart the game. How do I make the game restart?
I've tried as many solutions as possible and have ended up with this code. Including continue, break, and several other obvious options.
import time
def start():
score = 0
print("Welcome to Atlantis, the sunken city!")
time.sleep(1.5)
print("You are the first adventurist to discover it!")
time.sleep(1.5)
print("Do you explore or talk to the merpeople?")
time.sleep(1.5)
print("Type 1 to explore Atlantis alone.")
time.sleep(1.5)
print("Type 2 to talk to the resident merpeople.")
start()
def surface():
print("You return to the surface.")
print("When you go back to Atlantis it's gone!")
print("Your findings are turned to myth.")
print("The end!")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = -1
def castle():
print("The merpeople welcome you to their castle.")
print("It is beautiful and you get oxygen.")
print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
score = 1
print("To explore alone enter 5. To go to the surface enter 6.")
def drowndeath():
print("You begin to explore around you.")
print("You avoid the merpeople who avoid you in return.")
print("But, OH NO, your oxygen begins to run out!")
print("You run out of air and die.")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = 4
def merpeople():
print("The merpeople talk kindly to you.")
print("They warn you that your oxygen tank is running low!")
print("You can follow them to their castle or go back to the surface.")
print("Type 3 to go to the castle or 4 to go to the surface.")
score = 5
def alone():
print("You begin to explore alone and discover a secret caven.")
print("You go inside and rocks trap you inside!")
print("You die underwater.")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = 6
def famous():
print("You come back to land with new discoveries!")
print("Everyone loves you and the two worlds are now connected!")
print("You win!")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
def choice_made():
choice = input("Make your decision!\n ")
if choice == "1":
drowndeath()
elif choice == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice_made()
choice_made()
def choice2_made():
choice2 = input("What do you do?\n ")
if choice2 == "4":
surface()
elif choice2 == "3":
castle()
elif choice2 == "yes":
start()
elif choice2 == "no":
exit()
else:
print("Please enter a valid answer.")
choice2_made()
choice2_made()
def choice3_made():
choice3 = input("Make up your mind!\n ")
if choice3 == "5":
alone()
if choice3 == "6":
famous()
else:
print("Please enter a valid answer.")
choice3_made()
choice3_made()
def restart_made():
restart = input("Type your answer!\n ")
if restart == "yes":
sys.exit()
elif restart == "no":
exit()
else:
print("Please choose yes or no!")
restart_made()
restart_made()
while True:
choice = input("Make your decision!\n ")
if choice == "1":
drowndeath()
elif choice == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice_made()
choice_made()
while True:
choice2 = input("What do you do?\n ")
if choice2 == "4":
surface()
if choice2 == "3":
castle()
else:
print("Please enter a valid answer.")
choice2_made()
choice2_made()
while True:
choice3 = input("Make up your mind!\n ")
if choice3 == "5":
alone()
if choice3 == "6":
famous()
if choice3 == "1":
drowndeath()
if choice3 == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice3_made()
choice3_made()
while True:
restart = input("Type your answer!\n ")
if restart == "yes":
sys.exit()
elif restart == "no":
exit()
else:
print("Please choose yes or no!")
restart_made()
restart_made()
I want for my code to restart completely when 'yes' is typed after given the option.
In general, if you want to be able to 'go back to the beginning' of something, you want to have a loop that contains everything. Like
while True:
""" game code """
That would basically repeat your entire game over and over. If you want it to end by default, and only restart in certain situations, you would do
while True:
""" game code """
if your_restart_condition:
continue # This will restart the loop
if your_exit_condition:
break # This will break the loop, i.e. exit the game and prevent restart
""" more game code """
break # This will break the loop if it gets to the end
To make things a little easier, you could make use of exceptions. Raise a RestartException whenever you want to restart the loop, even from within one of your functions. Or raise an ExitException when you want to exit the loop.
class RestartException(Exception):
pass
class ExitException(Exception):
pass
while True:
try:
""" game code """
except RestartException:
continue
except ExitException:
break
break
You have two main options.
First option: make a main function that, when called, executes your script once. Then, for the actual execution of the code, do this:
while True:
main()
if input("Would you like to restart? Type 'y' or 'yes' if so.").lower() not in ['y', 'yes']:
break
Second, less compatible option: use os or subprocess to issue a shell command to execute the script again, e.g os.system("python3 filename.py").
EDIT: Despite the fact this is discouraged on SO, I decided to help a friend out and rewrote your script. Please do not ask for this in the future. Here it is:
import time, sys
score = 0
def makeChoice(message1, message2):
try:
print("Type 1 "+message1+".")
time.sleep(1.5)
print("Type 2 "+message2+".")
ans = int(input("Which do you choose? "))
print()
if ans in (1,2):
return ans
else:
print("Please enter a valid number.")
return makeChoice(message1, message2)
except ValueError:
print("Please enter either 1 or 2.")
return makeChoice(message1, message2)
def askRestart():
if input("Would you like to restart? Type 'y' or 'yes' if so. ").lower() in ['y', 'yes']:
print()
print("Okay. Restarting game!")
playGame()
else:
print("Thanks for playing! Goodbye!")
sys.exit(0)
def surface():
print("You return to the surface.")
print("When you go back to Atlantis it's gone!")
print("Your findings are turned to myth.")
print("The end!")
def castle():
print("The merpeople welcome you to their castle.")
print("It is beautiful and you get oxygen.")
print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
def drowndeath():
print("You begin to explore around you.")
print("You avoid the merpeople who avoid you in return.")
print("But, OH NO, your oxygen begins to run out!")
print("You run out of air and die.")
def merpeople():
print("The merpeople talk kindly to you.")
print("They warn you that your oxygen tank is running low!")
print("You can follow them to their castle or go back to the surface.")
def alone():
print("You begin to explore alone and discover a secret caven.")
print("You go inside and rocks trap you inside!")
print("You die underwater.")
def famous():
print("You come back to land with new discoveries!")
print("Everyone loves you and the two worlds are now connected!")
print("You win!")
def playGame():
print("Welcome to Atlantis, the sunken city!")
time.sleep(1.5)
print("You are the first adventurer to discover it!")
time.sleep(1.5)
print("Do you explore or talk to the merpeople?")
time.sleep(1.5)
ans = makeChoice("to explore Atlantis alone", "to talk to the resident merpeople")
if ans == 1:
drowndeath()
askRestart()
merpeople()
ans = makeChoice("to go to the castle", "to return to the surface")
if ans == 2:
surface()
askRestart()
castle()
ans = makeChoice("to return to the surface", "to explore alone")
if ans == 1:
famous()
else:
alone()
askRestart()
playGame()

User input comparison isn't working

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(“”).

Why will this program not work in the shell, but work in my IDE?

Im having a problem with a dice roller program (text for now but eventually graphical). It will not work in anything except for the IDE I use, Wing IDE 101 4.1. The error i get flashes too fast for me to read, but i will try to take a screenshot of it. (I will edit this post if i get a screenshot.)
Here is the program:
import random
#variables
available_dice = "D20"
main_pgm_start = False
#definitions of functions
def diePick():
print("Pick a die. Your choices are: ", available_dice)
print("")
which_dice = input("")
if which_dice == "D20" or which_dice == "d20":
rollD20()
else:
print("Error: Please try again")
print("")
diePick()
def rollD20():
print("Rolling D20 .... ")
print("")
d20_result = random.randrange(1, 20)
print("You have rolled a ", d20_result)
print("")
print("Would you like to roll again?")
print("")
y = input("")
if y == "y" or y == "Y" or y == "yes" or y == "Yes":
print("")
diePick()
def MainProgram():
print("Benjamin Ward's Random D&D Dice Roller")
print("")
x = input(" Press Enter to Continue")
print("")
diePick()
MainProgram()
You can redirect the log to the text file with "logging" module if my memory serves.
I dont think input() does what you expect it to. input reads a line of text, then executes it (as python).
I think what you want is more along the lines of stdin.readline(). To use it, you will have to from sys import stdin at the top, then replace all occurences of input with sys.readline(). Note also that this will return a newline at the end, which you have to account for.

Categories