local variable 'fight_run' referenced before assignment - python

ive been looking around but ive been unable to fix this error.
also as a side problem before this error the program would always print your week was average nothing much happened and the other 2 variables that could of happened didn't
this is all in python
from random import randint
import time
money = 2000
week = 0
def stockmarket():
global money
global week
stock = int(randint(1,50))
fight_random = int(randint(1,4))
fight = int(randint(1,100))
gain_lose = int(randint(1,2))
win_lose_var = int(randint(1,30))
luck = int(0)
if money > 10000 :
print ("""congratulations you beat the game by earning 10,000
now that you have so much money you can go back to your life as a hip hop artist """)
time.sleep(4)
print("it took you ",week,"weeks's to compleate the game")
print("can you do it faster next time")
else:
print(" you have gained lots of money",money,"")
print("you must now invest it all the stock market")
human_stock = int(input("please pick a number between 1-100 not that it matters as the markets are rigged: "))
#need to make the user number matter
change1 = int(stock-40+luck)
change2 = float (change1/100)
change3 = float (1-change2)
money = money * change3
week = week+1
print ("you have" , money,"")
week = week +1
#THIS IS WHERE THE PROBLEM STARTS!
if fight == 3:
print("bad luck")
fight_run = str(input("""late at night you get approched by a bunch of bad, bad people. they attempt to mugg you but you see there is a chance to run away but you could fight
them and gain lots of money! do you fight or run"""))
if fight_run == "run":
print("you fled the scene but left some money behind which has been stolen.")
money *=.8
print(" ",money," ")
stockmarket()
if fight_run == "fight" :
print ("you chose to fight the oncoming enemys!")
if fight < 0 or fight > 11:
print("you where over powered by your enemys and died")
time.sleep(5)
quit()
elif fight <10 and fight >80 :
win_lose = int(input("the fight is close and you are both weak. /n please pick and number between 1 and 30 for a chance to gain money!"))
elif gain_lose == 1:
print("you deafeated your attacckers and take there money (its not a crime if no one saw)")
money_fight_win = (win_lose/100)+ 1
money = money * money_fight_win
print ("",money,"")
elif gain_lose == 2 :
print ("your attacker won and they took your money luckly you hide some just before the fight ")
money_fight_lose = (win_lose/100)+ 1 - (winlose/50)
money = money * money_fight_lose
else :
print("you mortaliy wounded the atackers (cause ur dench m8) and took their money")
money = money *1.5
#loop
stockmarket()
if fight == 4:
print ("you found a lucky penny and added it to your penny collection")
luck = +1
elif fight == 1 or 2:
print("your week was average nothing much happened")
#loop
stockmarket()
#gets program to start
stockmarket()

What if the value of fight is 1?
Then if fight == 3 is false, so the creation of the variable fight_run is skipped, so the variable fight_run doesn't exist. Then you are testing if fight_run == "run" and you are being told fight_run doesn't exist.
I think what you want to do is to indent the code:
if fight_run == "run":
print("you fled the scene but left some money behind which has been stolen.")
money *=.8
print(" ",money," ")
stockmarket()
if fight_run == "fight" :
print ("you chose to fight the oncoming enemys!")
So that it is part of the if fight == 3 block.
Instead of a long sequence of 'if's, I would also look at using elif and else and maybe putting the input in a loop. What if I typed "pee my pants" instead of "run" or "fight"?

Your immediate problem is indentation level. So, if fight != 3, then fight_run is never declared or set. So when you check fight_run in the next if statement there is a chance that it might not exist. Fix your indentation so it reads.
if fight == 3:
print("bad luck")
fight_run = str(input("""late at night you get approched by a bunch of bad, bad people. they attempt to mugg you but you see there is a chance to run away but you could fight them and gain lots of money! do you fight or run"""))
if fight_run == "run":
print("you fled the scene but left some money behind which has been stolen.")
money *=.8
print(" ",money," ")
stockmarket()
if fight_run == "fight" :
print ("you chose to fight the oncoming enemys!")
This way, if fight == 3, then the player is approached, then depending on the player choice he can fight or run. Addressing this will get you to your next error, your code has a bunch of issues, including some more indentation level issues like this one.
Regarding the other issue you mentioned, when you do elif fight == 1 or 2:, that will always be true because testing 2 as a boolean will always be true. This would need to be elif fight == 1 or fight == 2:.
Also, as Robert said in his answer, you have several fall through situations here where the user can input an instruction that will not match any checks. You should always verify that you the instruction cannot fall through and do nothing.

Related

How do I fix my algorithm from messing up my input in my choose your own adventure game?

I'm working on a choose your own adventure text game on python and I added an algorithm that makes it so if you press the H key your hunger is shown and if you press T the time left is shown. But when I run my code the script runs but after the first input option is entered for your name, the breakfast yes/no input question gets printed again and again no matter what is entered. When i delete my algorithm, it runs fine and goes into the next step. I know I probably made a very stupid mistake but I am fairly new and I would greatly appreciate it if I could get some help. Thank you!
My code:
import keyboard
hunger = 100
timeLeft = 100
yes_no = ["yes", "no"]
breakfast = ["eggs", "cereal"]
name = input("What is your name?\n")
print("Hello, " + name + "! This is the BREAKFAST STORY.")
answer = ""
while answer not in yes_no:
answer = input("You wake up one morning and are very hunrgy, do you get breakfast? (yes/no?)")
if answer == "yes":
print("You enter the kitchen, your hunger gets worse every second.")
elif answer == "no":
print("You starve to death. The End!")
quit()
answer = ""
while answer not in breakfast:
answer = input("What do you eat? (eggs/cereal?) ")
if answer == "eggs":
print("Good job! You fed yourself, you stayed alive and you live a happy life")
quit()
elif answer == "cereal":
print("Sorry, the cereal was 10 years overdue, you die terribly!. Rest in peace,"+ name +".")
quit()
#algorithm
if(keyboard.is_pressed('t')):
timeLeftFunction()
elif(keyboard.is_pressed('h')):
hungerFunction()
def timeLeftFunction():
timeLeft -= 20
print("TIME LEFT:"+timeLeft+"%")
def hungerFunction():
hunger -= 30
print("HUNGER"+"%")

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

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

Simple choice game Python IDLE 3.4 How to proceed with different choices?

I'm very new to programming and was doing a simple choice game:
Answer = (input("You meet a bear, what do you do? A) Give the bear a hug B) Run away"))
if Answer == ("A)"):
print("The bear chopped your hand off!")
else:
print("Good choice, but the bear is running after you")
But how do I go on? Like add an option after having proceeded with a chopped of hand or running through the forest (2 choices at least for both previous outcomes)
Here is a start you can hopefully figure out how to expand on :)
def main():
print("Tristan Aljamaa's Simple Python Choice Game")
print("===========================================")
print("Instructions: Type A) or B) etc. whenever prompted\n")
game()
def game():
Answer = (input("You meet a bear, what do you do?\n A) Give the bear a hug\n B) Run away \nEnter A) or B):"))
if Answer == ("A)"):
print("The bear chopped your hand off!")
player_died()
else:
print("Good choice, but the bear is running after you")
player_ran()
def player_died():
print("You died, the bear eventually ate you...")
Answer = (input("Game Over!\n\nEnter N) for New Game:"))
if Answer == ("N)"):
main()
else:
print("Good Bye!")
def player_ran():
Answer = (input("You find an exit from the forest, what do you do\n A) Exit forest\n B) Run around in forest \nEnter A) or B):"))
if Answer == ("A)"):
print("You exited the forest")
player_crossedRoad()
else:
print("You (although insanly) chose to run around in the forest")
player_stillRunsinForest()
def player_crossedRoad():
print("You get the idea...")
main() #for testing on this online editor use the below line when calling the .py file on your computer
if __name__ == "__main__":main()
Try the game out here
You could create different functions/procedures for different cases. For example:
def choppedHand():
selection = input("The bear chopped your hand off! What do you do now? \n 1.Fight the bear with one hand.\n 2. Scream and search for help.\n 3. Cry and beg for mercy")
if selection == "1":
fight()
elif selection == "2":
scream()
else:
cry()
def run():
selection = input ("Good choice, but the bear is running after you. What do you do now? 1.Run through the trees. 2.Run in the plain")
#etc etc, same as top.
Answer = (input("You meet a bear, what do you do?\n 1.Give the bear a hug.\n 2.Run away."))
if Answer == ("1"):
choppedHand()
else:
run()
This is just an example, but using functions you can create different options for different cases and call a function in other parts of your code. For example you character can lose his arm in a different situation and in this case you just need to recall you function choppedHand().
I hope this was what you were looking for.
def invalid():
print("Answer not valid")
def game():
Answer = input("You meet a bear, what do you do?\nA) Give the bear a hug\nB) Run away\n>? ")
if Answer == ("A"):
print("The bear chopped your hand off!")
Answer2 = input("The bear is still around you, what will you do?\nA) Bleed out and accept your fate\nB) Try to fight back\n>? ")
if Answer2 == ("A"):
print("You bled out and died")
elif Answer2 == ("B"):
print("You attempt to fight back\nYou have failed, and died")
elif Answer == ("B"):
Answer3 = input("You find a tree and the bear is still running, what do you do?\nA) Climb the tree\nB) Hide behind the tree\n>? ")
if Answer3 == ("A"):
print("You went up the tree, and the bear went away!")
print("You walked home and went to bed")
elif Answer3 == ("B"):
Answer4 = input("You fell down a hill and slid into a village, what do you do?\nA) Trade with a villager\nB) Head home\n>? ")
if Answer4 == ("A"):
Answer5 = input("There is only one merchant, will you trade?\nA) Yes\nB) No")
if Answer5 == ("A"):
print("You traded two gold coins for a sword made of strong steel")
print("You headed home")
elif Answer5 == ("B"):
print("You did not trade, so you headed home")
else:
invalid()
elif Answer4 == ("A"):
print("You headed home")
else:
invalid()
else:
invalid()
else:
invalid()
game()

Python- Variable Won't Subtract?

I'm trying to create a simple question and answer game in Python (version 3.3.2), but can't figure out how to make an expression work. The "health" and "oppHealth" variables seen below will not change as the program runs, or at least the string display won't show them changing. Source code:
import time
#Variables
health = 30
oppHealth = 30
playStr = str(health)
oppStr = str(oppHealth)
def startBattle():
print()
print('You face off against your opponent.')
print()
print("Your health is " + playStr + ".")
print("Your opponent's health is " + oppStr + ".")
time.sleep(2)
print()
print('The opponent attacks with Fire!')
time.sleep(2)
print()
attack = input('How do you counter? Fire, Water, Electricity, or Ice?')
if attack == ('Fire'):
print("You're evenly matched! No damage is done!")
time.sleep(3)
startBattle()
elif attack == ('Water'):
print("Water beats fire! Your opponent takes 5 damage!")
oppHealth - 5
time.sleep(3)
startBattle()
elif attack == ('Electricity'):
print("You both damage each other!")
health - 5
oppHealth - 5
time.sleep(3)
startBattle()
elif attack == ('Ice'):
print("Fire beats ice! You take 5 damage.")
health - 5
time.sleep(3)
startBattle()
startBattle()
I simply want to make the appropriate health variables decrease by 5- and for the health displaying strings to reflect the change- every time a battle occurs. If anyone can help me with this, I'd greatly appreciate it. Please let me know if I've excluded any information that might help you help me.
the lines
health - 5
oppHealth - 5
and similar, do not actually modify anything, to save the subtraction back in the variables, use the -= operator instead
health -= 5
or you can also say
health = health - 5
The above two examples both achieve the same result. When you just say health - 5 you don't actually save it anywhere.
In addition to this you will need to specify global at the top of your function to modify these values or you will get an error.
def startBattle():
global health
global oppHealth
# ... rest of function
Also you don't need the playStr and oppStr variables, you can print the numeric values like this:
print("Your health is", health, ".")
print("Your opponent's health is", oppHealth, ".")
These don't really need to be global at all though, they can be within the function, sitting in a loop, my version of your program would be this:
#!/usr/bin/env python3
import time
def startBattle():
# set initial values of healths
health = 30
oppHealth = 30
print('You face off against your opponent.', end='\n\n')
while health > 0 and oppHealth > 0: # loop until someone's health is 0
print("Your health is {0}.".format(health))
print("Your opponent's health is {0}.".format(oppHealth), end='\n\n')
time.sleep(2)
print('The opponent attacks with Fire!', end='\n\n')
time.sleep(2)
print('How do you counter? Fire, Water, Electricity, or Ice?')
attack = input('>> ').strip().lower()
if attack == 'fire':
print("You're evenly matched! No damage is done!")
elif attack == 'water':
print("Water beats fire! Your opponent takes 5 damage!")
oppHealth -= 5
elif attack == 'electricity':
print("You both damage each other!")
health -= 5
oppHealth -= 5
elif attack == 'ice':
print("Fire beats ice! You take 5 damage!")
health -= 5
else:
print("Invalid attack choice")
time.sleep(3)
if health <= 0 and oppHealth <= 0:
print("Draw!")
if health <= 0:
print("You lose")
else:
print("You win!")
startBattle()
Though I'd also get rid of all the sleeps. People don't enjoy waiting for a program to "do work" as much as you might think, it's just gonna cause people to click away.
Read a bit more about Python syntax. The correct way to change the value of a variable is, for example:
health = health - 5
oppHealth - 5 should be written as
oppHealth = oppHealth - 5
You're forgetting save the result of your computation

Categories

Resources