Why can't I break out of my loop? (Python) - python

import rando
move = rando.Moves()
All of this junk is just writing to a file to give some context about the game
oof = open('README.txt', 'w') #opens the text file
oof.write("The Final Adventure\n")
oof.write("\n") #writes text to the file
oof.write("This game is about an adventurer(you) trying to fight through a
dungeon in order to get the legendary sword of mythos.\n")
oof.write("\n")
oof.write("With this legendary sword you can finally rid your homeland of
the evil king of Mufasa and take the mantle of kingship.\n")
oof.write("\n")
oof.write("Best of luck to you, Warrior!\n")
oof.write("\n")
oof.write("You have 3 move options with any enemy you encounter.\n")
oof.write("\n")
oof.write("1 - Attack\n")
oof.write("2 - Run Away\n")
oof.write("3 - Talk\n")
oof.write("Have fun!!")
oof.close() #closes the file
print("Please read the README.txt in this file")
player = True
A buddy of mine told me I had to have two while loops so not too sure why I need those but it works slightly like it's meant to.
while True:
while player:
#First Door
print("You walk through the forest until you finally find the talked
about entrance door.")
print("There is a Gatekeeper standing by the entrance and in order
to enter you must defeat him")
print("")
move = int(input("What will you do?(Please use numbers 1-2-3 for
moves) "))
The problem is here. I have a module that I made that if the attack fails, you die and player gets set to False but it still continues the while loop.
if move == 1:
rando.Moves.move1(player)
elif move == 2:
rando.Moves.move2(player)
elif move == 3:
rando.Moves.move3(player)
else:
print("You ran out of time and died")
player = False
if player == False:
break
#First Room
print("The door suddenly opens and you walk through.")
print("")
print("After walking for a bit you discover a chest, probably full
of loot!")
print("You walk up and begin to open the chest and it clamps down on
your hand with razor sharp teeth.")
print("ITS A MONSTER!")
print("After struggling, you are able to free your hand.")
move = int(input("What will you do? "))
if move == 1:
rando.Moves.move1(player)
elif move == 2:
rando.Moves.move2(player)
elif move == 3:
rando.Moves.move3(player)
else:
print("You ran out of time and died")
player = False
#Play again
play = input("Want to play again? (y/n) ")
if play == "y":
player = True
elif play == "n":
print("Goodbye!")
break

You don't need two loops, just one.
while True:
if move == 1:
rando.Moves.move1(player)
elif move == 2:
rando.Moves.move2(player)
elif move == 3:
rando.Moves.move3(player)
else:
print("You ran out of time and died")
break
...
Your code was just breaking out of the inner loop, not the outer loop.

Related

How to make the program go back to the top of the code with a while loop?

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!")

Problem with python: how can I make something happen only some times that a definition is called upon?

So I have a text-adventure game for an intr Computer Science class & I need to put items in it. Inside of a definition, I have a global variable knife. But I need to make it so that it doesn't ask you to pick up the knife every time you walk into the room (or the definition is called upon) if you already have picked up the knife.
global knife
global knife_val
if knife_val = 1
knife = input("You step on the handle of a knife when walking into the room. Do you wish to pick it up?").lower()
if knife == "yes":
print("You picked up the Knife!")
knife_val = 0
then later it asks you
attack = input("Do you wish to attack?")
if attack == "yes":
move_miss = random.randint(1,5)
if move_miss == 1:
miss = True
else:
miss = False
if miss:
print("You missed!")
print("You are bitten by the monster and you die. Goodbye")
quit()
elif attack == "no":
print("You are bitten by the monster and you die. Goodbye")
quit()
print("You beat the monster!")
elif knife_val = 1:
print("You are bitten by the monster and you die. Goodbye")
quit()
how can I make it so that this only happens when the condition is met? when I tried before there was an error

I'm making a text based adventuere game in python and trying to add a third option but it's not working

I'm trying to make a simple text adventure game with three choices. But I can't seem to figure out why this isn't working.
This is the code I have been working on:
#Text based medieval adventure game
#Imported libraries are required
import random
import time
def displayWelcome():
print ("\nText adventure game\n")
print ("Welcome to the medieval adventure game!")
print ("You will have many choices through out this game")
print ("Be sure to pick the right one")
print (" Good Luck! ")
answer = askYesNo("Would you like help with this program? (Y/N): ")
if answer == "Y":
helpForUser()
time.sleep(3)
def askYesNo (question):
# This function will ask you a yes or no question and will keep asking until one is chosen.
# The following function is used to erase the variable response of any values
response = None
while response not in ("Y", "N"):
response = input (question).upper()
return response
def helpForUser():
#This function will show the user some helpful advice if they desire it
print ("\n+++++++++++++++++++++++++++++++++++++++ Help +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
print ("This game is a adventure text based game set in the medieval times")
print ("You will be asked multiple questions with a yes or no response")
print ("you must answer the questions with the answers supplied to you suches as yes or no")
print ("If you don't answer the q uestion with the given answers it will be repeated untill a valid response occurs")
print ("The program can end when you choose")
print ("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
def displayIntro():
#Displays intro to game
print ("\n It's been a rough day in the wild and you despratly need shelter")
print ("There is currently a war going on and nowhere is safe")
print ("But you intend to find somwhere with food and a bed but it wont be easy...")
print ()
def choosePath(lower,middle,upper):
#This functions allows you to choose between multiple options
path = 0
while path < lower or path > upper:
number = input("What path will you take(" + str(lower) + " - " + str(upper) + ")?: ")
if number.isdigit():
path = int (number)
else:
path = 0
return path
def followPath(chosenPath):
print ("you head down a long road\n")
time.sleep(3)
print ("You come across an abandoned campsite and decide to stay there for the night")
time.sleep(3)
print("You wake up to a sudden sound of voices and begin to realise that this campsite wasn't abandoned...")
time.sleep(3)
print("You start to freak out")
time.sleep(3)
if chosenPath == 1:
print("You grab your sword out and decide to go out the tent")
print ("Four well trained knights surround you")
print ("They strike without any hesitation, you counter two knights trying to hit you from the front as two from behind stab you in the back")
print ("The knights decide to burn your body and leave nothing left of you.\n")
elif chosenPath == 2:
print("You dart out of the tent and head for the exit")
print("All the guards try and get you whilst shooting arrows")
print("Several arrows hit you leaving you injured unable to run")
print ("Suddenly a man with a giant axe appears before you and slices you head off in a clean swoop\n")
else chosenPath == 3:
print("You keep calm and decide to sneak past all the guards")
print ("You're close to the exit when suddenly a guard notices you")
print("He's about to call for back up when you dash right into his chest with your sword, leaving it in him and running out the campsite")
print("You make it to a safe forest and decide to rest\n")
displayWelcome()
playAgain = "Y"
while playAgain == "Y":
displayIntro()
choice = choosePath()
followPath(choice)
playAgain = askYesNo ("Would you like to play again?")
print ("\nBye")
Error Number one: line 63, else should be elif or get rid of the condition "chosenPath == 3:
Current state
else chosenPath == 3:
What it should look like
elif chosenPath == 3:
or
else:
The other error is that nothing ever happens on initialization of choice because you forgot to input the "lower, middle, upper" values.

Python coding for online Game - Pizzeria chose story Game.

I am stayed in getting the right coding. If you happen to run this code, please correct what you see fit. I have searched and there continues to be bugs here and there. Here is the game coding. There may be some issues in the definition terms and I'm still learning the Python vocabulary to defined new items and am not finding right answers. Here is the code that you can run and try. Thank you:
import random
import time
def displayIntro():
print("You are in a city. In front of you,")
print("you see two restraunts. In one pizzeria, the service is friendly")
print("and will share thier free pizza with you. The other pizzeria")
print("is very unpredictable and will hire you to wash the dishes in the back quick.!")
print()
def choosePizzeria():
pizzeria=""
while((pizzeria != "1") and (pizzeria != "2")):
print("Which pizzeria will you go into? (1 or 2) ")
pizzeria = input()
return pizzeria
def checkPizzeria(level,(pizzeria != "1") or (pizzeria != "2")):
print("You approach the pizzeria and see people hustling in and out quickly...")
time.sleep(2)
print("It really crowded with people waiting in line, playing arcade games and just having a good time dancing...")
time.sleep(2)
print("A little manager with a suit steps in in front of you! He quickly slips his arm behind his back...")
print()
time.sleep(2)
friendlypizzeria = random.randint(1, 3)
overworkPizzeria = friendlypizzeria + 1
if overworkPizzeria > 3:
overworkPizzeria -= 3
if chosenPizzeria == str(friendlyPizzeria):
print("Hand you a slip of paper for two free pizzas!")
elif chosenPizzeria == str(overworkPizzeria):
print("He hands you a slip of paper telling you to watch the dishes in the back for a while since you stared at him too long!")
else:
level += 1
if level < 3:
print("You quickly hid behind some customes and head out to 3 more pizzerias")
else:
print("Congratulations you win two free pizzas and")
print("you get to go to the manager's weekend party!!!! ")
return level
playAgain = "yes"
while playAgain == "yes" or playAgain == "y":
displayIntro()
level = 0
pizzeriaNumber = choosePizzeria()
level = checkPizzeria(level,pizzeriaNumber)
if level == 1:
pizzeriaNumber = choosePizzeria()
level = checkPizzeria(level,pizzeriaNumber)
if level == 2:
pizzeriaNumber = choosePizzeria()
level = checkPizzeria(level,pizzeriaNumber)
print('Do you want to play again? (yes or no)')
playAgain = input()
Thank you.
Mostly Syntax errors, I would suggest reading some Python documentation. Especially in regards to Types, and Comparison Operators. But below will run;
import random
import time
def displayIntro():
print("You are in a city. In front of you,")
print("you see two restraunts. In one pizzeria, the service is friendly")
print("and will share thier free pizza with you. The other pizzeria")
print("is very unpredictable and will hire you to wash the dishes in the back quick.!")
print()
def choosePizzeria():
pizzeria=""
while((pizzeria != 1) and (pizzeria != 2)):
print("Which pizzeria will you go into? (1 or 2) ")
pizzeria = input()
return pizzeria
def checkPizzeria(level, pizzariaNumber):
print("You approach the pizzeria and see people hustling in and out quickly...")
time.sleep(2)
print("It really crowded with people waiting in line, playing arcade games and just having a good time dancing...")
time.sleep(2)
print("A little manager with a suit steps in in front of you! He quickly slips his arm behind his back...")
print()
time.sleep(2)
chosenPizzeria = pizzariaNumber
friendlypizzeria = random.randint(1, 3)
overworkPizzeria = friendlypizzeria + 1
if overworkPizzeria > 3:
overworkPizzeria -= 3
if chosenPizzeria == friendlypizzeria:
print("Hand you a slip of paper for two free pizzas!")
elif chosenPizzeria == overworkPizzeria:
print("He hands you a slip of paper telling you to watch the dishes in the back for a while since you stared at him too long!")
else:
level += 1
if level < 3:
print("You quickly hid behind some customes and head out to 3 more pizzerias")
else:
print("Congratulations you win two free pizzas and")
print("you get to go to the manager's weekend party!!!! ")
return level
playAgain = "yes"
while playAgain == "yes" or playAgain == "y":
displayIntro()
level = 0
pizzeriaNumber = choosePizzeria()
level = checkPizzeria(level,pizzeriaNumber)
if level == 1:
pizzeriaNumber = choosePizzeria()
level = checkPizzeria(level,pizzeriaNumber)
if level == 2:
pizzeriaNumber = choosePizzeria()
level = checkPizzeria(level,pizzeriaNumber)
print('Do you want to play again? (yes or no)')
playAgain = raw_input()

How can I check to see what a user input in a different function?

This is my first post on stackoverflow and I'm only asking because I truly am stuck. A good friend and I are trying to make a simple text based game(let's hear it for the 80's). It's my first day essentially with python and I've run into a problem. The player has a choice to pick up a dagger or to not. Later on I want this decision to come into play. Except I've no idea how to check and see what said player entered!
Here's my code
Note:It crashes in the state it's in right now mainly because of me stumbling around trying to get this problem fixed.
def start():
print("You wake up in a dank tunnel reeking of death and decomposition,")
print("you have no weapons to defend yourself with.")
time.sleep(1)
print("\n")
print("You head north and find yourself at a four way tunnel.")
print("\n")
print("Down the west tunnel, you hear sounds which could have only come")
print("from hell itself. With every sound uttered, your fear grows.")
time.sleep(1)
print("\n")
print("Down the north tunnel, there is a room with a glimmering object")
print("lying on the ground.")
time.sleep(1)
print("\n")
print("Down the East tunnel, there appears to have been a cave in.")
time.sleep(1)
print("\n")
print("The South tunnel is the way you just came. \n")
time.sleep(1)
while True:
r3 = input("Which way would you like to go?\n")
if r3 == "west" or r3 == "West":
print("The sounds are becoming Louder, do you continue or head back?")
while True:
w1 = input("")
if w1 == "continue" or w1 == "Continue" or w1 == "west":
print("You continue further on...")
time.sleep(2.5)
westtunnel()
elif w1 == "head back" or w1 == "Head Back" or w1 == "back" or w1 == "Back":
print("\n")
print("The voices congregate behind you. No way your going back that way!\n")
time.sleep(1)
westtunnel()
else:
print("\n")
print("You couldn't possibly do anything else.\n")
time.sleep(1)
print("Greater minds prevail and you continue westward...\n")
time.sleep(2)
westtunnel()
elif r3 == "north" or r3 == "North":
print("You find a rusty dagger on the floor, stained with blood.")
print("Do you want to pick up the dagger?")
print("1: Yes, that seems useful!")
print("2: No, I'm a bit of a pacifist you see.")
while True:
pd = input("")
if pd == "1":
print("You slowly picked up the dagger.")
number = int(pd)
break
else:
print("You left the dagger. All alone.")
number = int(pd)
break
print("You can go only go back the way you came.\n")
time.sleep(1)
print("You head back to the four way tunnel.")
elif r3 == "east" or r3 == "East":
print("\n")
print("You can not go that way, there are rocks there. We told you this.\n")
time.sleep(1)
print("You go back to the four way tunnel")
elif r3 == "south" or r3 == "South":
print("\n")
print("This is the room you awoke in, there is nothing of interest.\n")
time.sleep(1)
print("You head back to the four way tunnel")
else:
print("\n")
print("You run into a corner, you hurt yourself in confusion. \n")
time.sleep(1)
print("You stumble back to the four way.")
def ladder():
print("Do you have a dagger?!")
number = pd
if number == "1":
print("Good you have it!")
start()
input("")
else:
print("awh...no dagger for you...")
start()
input("")
if __name__ == '__main__':
menu()
Look into Python classes.
You probably want to create a Game State object that holds the results of decisions made in the course of the game. Then, later, when the results of those decisions matter, you check the state.
You will need to keep a reference to that game state object during your main game loop. However, keeping it in one object keeps all the state information organized, instead of keeping references to several disparate variables.

Categories

Resources