Script not looping in python - python

I've being making a small escape room project and when you complete an action it's supposed to loop upon completion of certain actions it is supposed to loop but my code won't do that. Can someone help me fix it? This is my code. Link: (https://replit.com/#HoloGrain/Escape-Room-or-Bigger-Project#main.py)
inventory= []
HP=100
ImplacedAnemo= False
ImplacedGeo= False
ImplacedElectro= False
print("Type every word beggining with a capital letter")
def Help():
print("Commands:")
print("Pick Up (Item))")
print("Throw (Item) At (Other item)")
print("Press (Item)")
print("Hit (Item)")
print("Open (Place)")
print("Use (Item), (Command can only be used in battles)")
print("Use (Item) On (Item or Door(ex. Room 1 Door))")
print("Inventory", "(Opens inventory)")
print("Check HP", "(Checks HP)")
def start():
print("Welcome to HoloGrain's Escape room")
print("You are locked in Tenshukaku")
def Room1():
print("Paimon: Where are we")
print("You: I don't know")
print("Paimon: We should get out")
def Room1Command():
ChainsLocked = True
print("Room 1 Tools: Glass cage (contains sword), Paimon (If you get hungry and talks), Rock, Door (locked using a sword lock), Chains (Locked using sword lock)")
print("You're chained to the floor")
Room1Start = input("What do you want to do?: ")
if Room1Start == "Pick Up Rock":
for x in inventory:
if x == "Rock":
print("Action: Hey, don't even try")
Room1Command()
elif x == "Dull Blade":
print("Hey, don't even try")
Room1Command()
else:
inventory.append("Rock")
print("You have picked up a rock")
Room1Command()
elif Room1Start == "Throw Rock At Glass Cage":
for x in inventory:
if x == "Rock":
print("Action: You succesfully threw the rock it shatters the cage and you get the dull blade (6 DMG) and can ")
inventory.remove('Rock')
inventory.append("Dull Blade")
else:
print("You don't have a Rock to throw")
elif Room1Start == "Use Dull Blade On Chains":
for x in inventory:
if x == "Dull Blade":
if ChainsLocked == True:
ChainLocked = False
inventory.append("Chains")
print("You have unlocked the chains (Can stop one attack from an enemy and restarts mega-skills cooldown (One-time use)) and taken them")
else:
print("Action: You've done this already")
elif Room1Start == "Check HP":
print(HP)
Room1Command()
elif Room1Start == "Check Inventory":
print(inventory)
Room1Command()
elif Room1Start == "Use Dull Blade On Door":
for x in inventory:
if x == "Dull Blade":
if ChainLocked == False:
print("You've opened the door")
else:
print("That doesn't work")
else:
print("Action: Undefined action in current state")
Room1Command()
Help()
start()
Room1()
Room1Command()

Fo
elif Room1Start == "Throw Rock At Glass
You don't have a "Room1Commande() at the end

So the first thing I see is that you're looping through an empty list - so that's not happening.
Perhaps you mean something like this:
def Room1Command():
ChainsLocked = True
print(
"Room 1 Tools: Glass cage (contains sword), Paimon (If you get hungry and talks), Rock, Door (locked using a sword lock), Chains (Locked using sword lock)"
)
print("You're chained to the floor")
Room1Start = input("What do you want to do?: ")
if Room1Start == "Pick Up Rock":
if len(inventory) == 0 or "Rock" not in inventory:
inventory.append("Rock")
print("You have picked up a rock")
Room1Command()
else:
do_something_else()

There isn't any loop in your code. It just calls all the functions once, and it's over.
If you want the Room1Command to be always running, you can just easily add Room1Command() in the last line of Room1Command function. So it would look like this :
def Room1Command():
ChainsLocked = True
print("Room 1 Tools: Glass cage (contains sword), Paimon (If you get hungry and talks), Rock, Door (locked using a sword lock), Chains (Locked using sword lock)")
print("You're chained to the floor")
Room1Start = input("What do you want to do?: ")
if Room1Start == "Pick Up Rock":
for x in inventory:
if x == "Rock":
print("Action: Hey, don't even try")
Room1Command()
elif x == "Dull Blade":
print("Hey, don't even try")
Room1Command()
else:
inventory.append("Rock")
print("You have picked up a rock")
Room1Command()
elif Room1Start == "Throw Rock At Glass Cage":
for x in inventory:
if x == "Rock":
print("Action: You succesfully threw the rock it shatters the cage and you get the dull blade (6 DMG) and can ")
inventory.remove('Rock')
inventory.append("Dull Blade")
else:
print("You don't have a Rock to throw")
elif Room1Start == "Use Dull Blade On Chains":
for x in inventory:
if x == "Dull Blade":
if ChainsLocked == True:
ChainLocked = False
inventory.append("Chains")
print("You have unlocked the chains (Can stop one attack from an enemy and restarts mega-skills cooldown (One-time use)) and taken them")
else:
print("Action: You've done this already")
elif Room1Start == "Check HP":
print(HP)
Room1Command()
elif Room1Start == "Check Inventory":
print(inventory)
Room1Command()
elif Room1Start == "Use Dull Blade On Door":
for x in inventory:
if x == "Dull Blade":
if ChainLocked == False:
print("You've opened the door")
else:
print("That doesn't work")
else:
print("Action: Undefined action in current state")
Room1Command()
Room1Command()
By doing this, everytime the user enters a command and it gets processed, your code will be waiting for the next input. Which means there would be a loop on your Room1Command function. If I've understood your issue properly, I think this would work.
Also keep in mind that the list called Inventory is empty, so you can't iterate over it. You should put some values inside it first.

Related

I have a bug in my program that I cannot figure out

So, I just recently started coding and decided to make a rock paper scissors game; However, my program has a bug where if the user enters "rock" the correct code block doesn't run. Instead it runs an else statement that's only meant to run when the user enters, "no". I tried using a while loop instead of just if else statements but it didn't make a difference.
import random
q_1 = str(input("Hello, want to play Rock Paper Scissors?:"))
print()
# ^^adds an indent
rpc_list = ["rock", "paper", "scissors"]
comp = random.choice(rpc_list)
# ^^randomly selects r, p, or s
user = str(input("Great, select Rock Paper or Scissors:"))
if q_1 != "yes":
if q_1 == comp:
print("Oh No, a Tie!")
elif q_1 == "rock":
if comp == "paper":
print("I Win!")
else:
print("You Win!")
elif q_1 == "paper":
if comp == "rock":
print("You Win!")
else:
print("I Win!")
else:
if comp == "rock":
print("I Win!")
else:
print("You Win!")
else:
print("Ok :(")
There are a few issues with your code.
First of all your code only plays the game if the user doesn't enter "yes". You need to change if q_1 != "yes": to if q_1 == "yes":.
Secondly, your code asks the user to choose rock, paper or scissors regardless of whether they have said they want to play or not. Fix this by moving user = str(input("Great, select Rock Paper or Scissors:")) to under the if q_1 == "yes": if statement.
Thirdly, your code uses q1 instead of user as it should.
Here is how your code should look:
import random
q_1 = str(input("Hello, want to play Rock Paper Scissors?:"))
print()
# ^^adds an indent
rpc_list = ["rock", "paper", "scissors"]
comp = random.choice(rpc_list)
# ^^randomly selects r, p, or s
if q_1 == "yes":
user = str(input("Great, select Rock Paper or Scissors:"))
if user == comp:
print("Oh No, a Tie!")
elif user == "rock":
if comp == "paper":
print("I Win!")
else:
print("You Win!")
elif user == "paper":
if comp == "rock":
print("You Win!")
else:
print("I Win!")
else:
if comp == "rock":
print("I Win!")
else:
print("You Win!")
print("I played:",comp)
else:
print("Ok :(")

Rock Paper Scissors Running Twice Error

I'm new to programming. I have written code for the rock paper scissors game but there is one bug that I can't seem to fix. When the game closes, the user is asked if he wants to play again. If the user answers yes the first time, then plays again then answers no the second time, the computer for some reason asks the user again if he wanted to play again. The user must enter no in this case. This is because although the user answers no, the answer gets reset to yes and goes over again. How can this be fixed?
# This code shall simulate a game of rock-paper-scissors.
from random import randint
from time import sleep
print "Welcome to the game of Rock, Paper, Scissors."
sleep(1)
def theGame():
playerNumber = 4
while playerNumber == 4:
computerPick = randint(0,2)
sleep(1)
playerChoice = raw_input("Pick Rock, Paper, or Scissors. Choose wisely.: ").lower()
sleep(1)
if playerChoice == "rock":
playerNumber = 0
elif playerChoice == "paper":
playerNumber = 1
elif playerChoice == "scissors":
playerNumber = 2
else:
playerNumber = 4
sleep(1)
print "You cookoo for coco puffs."
print "You picked " + playerChoice + "!"
sleep(1)
print "Computer is thinking..."
sleep(1)
if computerPick == 0:
print "The Computer chooses rock!"
elif computerPick == 1:
print "The Computer chooses paper!"
else:
print "The Computer chooses scissors!"
sleep(1)
if playerNumber == computerPick:
print "it's a tie!"
else:
if playerNumber < computerPick:
if playerNumber == 0 and computerPick == 2:
print "You win!"
else:
print "You lose!"
elif playerNumber > computerPick:
if playerNumber == 2 and computerPick == 0:
print "You lose!"
else:
print "You win!"
replay()
def replay():
sleep(1)
playAgain = "rerun"
while playAgain != "no":
playAgain = raw_input("Would you like to play again?: ").lower()
if playAgain == "yes":
sleep(1)
print "Alright then brotha."
sleep(1)
theGame()
elif playAgain == "no":
sleep(1)
print "Have a good day."
sleep(1)
print "Computer shutting down..."
sleep(1)
else:
sleep(1)
print "What you said was just not in the books man."
sleep(1)
theGame()
This is because of the way the call stack is created.
The First time you play and enter yes to play again, you are creating another function call to theGame(). Once that function call is done, your program will continue with the while loop and ask if they want to play again regardless if they entered no because that input was for the second call to theGame().
To fix it, add a break or set playAgain to no right after you call theGame() when they enter yes
while playAgain != "no":
playAgain = raw_input("Would you like to play again?: ").lower()
if playAgain == "yes":
sleep(1)
print "Alright then brotha."
sleep(1)
theGame()
break ## or playAgain = "no"
You should break out of the loop after calling theGame. Imagine you decided to play again 15 times. Then there are 15 replay loops on the stack, waiting to ask you if you want to play again. Since playAgain is "yes" in each of these loops, each is going to ask you again, since playAgain is not "no"

Rock, Paper, Scissors - Python

I am trying to complete a rock, paper, scissors assignment for class.
I'm getting a "UnboundLocalError: local variable 'tied' referenced before assignment" error.
Can someone please tell me why I'm getting this error?
import random
user_score = 0
computer_score = 0
tied = 0
def main():
print ("Let's play the game of Rock, Paper, Scissors. ")
while True:
print ("Your current record is", user_score, "wins,", computer_score, "losses and", tied, "ties")
computer_choice = random.randint(1,3)
if computer_choice == 1:
computer_rock()
elif computer_choice == 2:
computer_paper()
else:
computer_scissors()
def computer_rock():
user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
if user_choice == "1":
print ("Draw! You both chose Rock.")
tied += 1
try_again()
elif user_choice == "2":
print ("You Win! The computer chose Rock, while you picked Paper.")
user_score += 1
try_again()
elif user_choice == "3":
print ("You Lose! You chose scissors, while the computer picked Rock.")
computer_score += 1
try_again()
else:
print ("ERROR: Invalid entry, please re-enter your choice. ")
computer_rock()
def computer_paper():
user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
if user_choice == "1":
print ("You Lose! You chose rock, while the computer picked Paper.")
computer_score += 1
try_again()
elif user_choice == "2":
print ("Draw! You both picked Paper.")
tied += 1
try_again()
elif user_choice == "3":
print ("You Win! The computer chose Paper, while you picked Scissors.")
user_score += 1
try_again()
else:
print ("ERROR: Invalid entry, please re-enter your choice. ")
computer_paper()
def computer_scissors():
user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
if user_choice == "1":
print ("You Win! You chose rock, while the computer picked Scissors.")
user_score += 1
try_again()
elif user_choice == "2":
print ("You Lose! The computer chose Scissors, while you picked Paper.")
computer_score += 1
try_again()
elif user_choice == "3":
print ("Draw! You both picked Scissors.")
tied += 1
try_again()
else:
print ("ERROR: Invalid entry, please re-enter your choice. ")
computer_scissors()
def try_again():
choice = input("Play again? Yes or no. ")
if choice == "y" or choice == "Y" or choice == "yes" or choice == "Yes":
main()
elif choice == "n" or choice == "N" or choice == "no" or choice == "No":
print ("Thanks for playing. ")
else:
print ("Try again")
try_again()
main()
Adding the following code as the first line in each of the three computer_() functions should fix your problem.
global tied, user_score, computer_score
There are better ways to accomplish what you're doing, but that should get you over the hump here :)
While Triptych's answer is perfectly acceptable (and also widely used), for a relatively novice-level programmer it is usually better practice to pass arguments into functions instead of utilizing the global keyword.
More info can be found at the Python Documentation: https://docs.python.org/3/tutorial/controlflow.html#defining-functions
In essence, the point is for the programmer to pass what is called an argument (or arguments) into the function, and the function containing those parameters can process this data and return values back to the location where it was called, similar to how the print() function works. You pass a string (ex. "Hi") into the print() function (ex. print("Hi")), and code within this built-in function displays the characters "Hi" onto the screen.
In this case, your code would look something like this:
# In your main function:
def main():
print ("Let's play the game of Rock, Paper, Scissors. ")
while True:
print ("Your current record is", user_score, "wins,", computer_score, "losses and", tied, "ties")
computer_choice = random.randint(1,3)
if computer_choice == 1:
result = computer_rock(user_score, computer_score, tied) ## Notice the difference here
elif computer_choice == 2:
result = computer_paper(user_score, computer_score, tied) ## Those variables you put in the function call are arguments
else:
result = computer_scissors(user_score, computer_score, tied)
# ...
# In the computer_rock() function:
# Even though I only modified this function, you should probably modify all three to suit your needs.
def computer_rock(user_score, computer_score, tied): ## <-- See the parameters?
user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
if user_choice == "1":
print ("Draw! You both chose Rock.")
tied += 1
try_again()
elif user_choice == "2":
print ("You Win! The computer chose Rock, while you picked Paper.")
user_score += 1
try_again()
elif user_choice == "3":
print ("You Lose! You chose scissors, while the computer picked Rock.")
computer_score += 1
try_again()
return [user_score, computer_score, tied] # Returning a list so it is easier to sort variables
Another thing to note, even though you are calling try_again() to restart the game, it is not a very good idea to call main() inside of a function that will be called by main(). It is better to use a while loop in the main function to regulate and control the flow of the program.
Hopefully this helped!
It caused from a feature in Python.
The following example emits the same Exception. Note that You can't assign to Global-Variable in Local-Scope.
>>> variable = 1
>>> def function():
... variable += 1
...
>>> function()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in function
UnboundLocalError: local variable 'variable' referenced before assignment
So if you write as the following, the value of Globale-Variable is not changed. This variable in function() is not Global-Variable but Local-Variable. Right?
>>> variable = 1
>>> def function():
... variable = 2
...
>>> function()
>>> variable
1
By the way, this feature is useful for us, because we want to use functions as small as possible, if speaking loudly, simply because we humans don't understand long functions.
Perhaps you want to use the Global-Variable here now, but when you write many and many codes, and can use Global-Variable, you will be panic such as "Where did this variable change?" because there are many places you changed.
If we have codes which we can't know where we change, these codes will be mysterious codes. It's so disgusting.
#Triptych 's answer is also right. If you adopt his answer, this codes will work. However I recommend that you don't use global.
p.s. You can do it in JavaScript.

Python text RPG error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm making a textual RPG, and I'm running into a problem. So in the code below, mobHP is a global variable, which is equal to 20000. This is only a part of the code. So what's happening is that once the attack takes place, the new HP of the monster is shown, but then by the second attack, the HP again becomes 20000 and then the damage is subtracted, and again another value is shown, it isin't subtracting from the new value itself. battlem() is the battle menu from where you can attack, use potions and run. win() is a def function to what to show when the user wins.
For example if a player hits the monster by 1000, then the currentHP will show as 19000, but then when I attack again, say hit by 1400, instead of 19000-1400, it subtracts from the original value, and becomes 18600.
Help would really be appreciated
def Attack():
damage = random.randint(120,240) - random.randint(80,120)
currentHP = 0
currentHP -= damage
input()
print("You swing your sword at the enemy!")
print("Inflicted damage:",damage,"enemy HP:",currentHP)
if playerHP <= 0:
death()
elif mobHP <= 0:
win()
else:
battlem()
currentHP=mobHP;
while(currentHP>0):
battlem()
However, this doesn't work as the output is
You swing your sword at the enemy!
Inflicted damage: 95 enemy HP: -95
This was a solution that was given, but then removed, and when I further asked for a solution nobody replied again.
FULL CODE:
import random
import time
global playerHP
global inventory
global mobHP
global mobSpeed
global mob
global boss
global level
global strength
global speed
global potions
global exp
global mithril
playerHP= 28000
level = 74
strength = 80
speed = 120
potions = 3
exp = 0
mithril = 10000
mobHP = 20000
mobstrength = 120
mobSpeed = 180
inventory = []
def prompt():
command = input("What action will you perfrom?")
return command
def death():
if playerHP== 0:
print("Your HP has been depleted completely")
input()
print("You are now dead")
input()
print("You will be respawned at the Misgauka")
input()
townone()
def townoned():
print("You are at the town of Misgauka")
print("What do you wish to do from here onwards")
print("""
Type Inn to go to the Inn
Type store to go to the store
Type grasslands to go hunt some monsters
Type dungeon to hunt harder monsters
""")
command = prompt()
if command == "Inn":
print("You are now at the Inn, what do you wish to do?")
input()
print("""You can do the following:
Rest
""")
command = prompt()
if command == "Rest":
rest()
if command == "Store":
print("You make your way to the store")
input()
print("Welcome to Tonajta's Weapon and Supplies shop")
input()
print("""You can do the following:
Display Catalogue
Exit store
""")
command = prompt()
if command == "Display" or "display":
print("Open the Weapons Catalogue or the Supplies catalogue")
input()
command = prompt()
if command == "Weapons":
wepmenu()
if command == "Supplies":
supplymenu()
elif command == "Exit":
print("Thanks for coming")
input()
print("Please do visit again")
input
townone()
def Grasslands():
print(" You have already cleared the Grasslands")
input()
print("You may go there to gain more experience")
input()
print("Y/N")
input()
command = prompt()
if command == "Y" or "y":
print("You proceed to the grasslands")
input()
elif command == "N" or "n":
townoned()
else:
print("You seem to be pressing the wrong command")
Grasslands()
def win():
print("You have managed to slain the enemy")
input()
print("You now must dwell further within the greenlands")
input()
def battles():
print("A wild boar appears in front of you")
input()
print("What do you choose to do?")
input()
print("Fight or Run?")
input()
command = prompt()
if command == "Fight" or "fight":
print("Good work senpai")
input()
battlem()
elif command == "Run" or "run":
print("You turn to run")
time.sleep(1)
print("The pathway behind you is now blocked")
input()
print("Thus, you must fight")
battlem()
else:
battles()
def boss_battle():
print("Let's fight")
input()
command = prompt()
if command == "Fight" or "fight":
print("You unsheath your sword")
input()
boss_battle_m()
else:
print("You can't run away from this")
input()
boss_battle_m()
def boss_battle_m():
print("""
1. Attack
2. Potions
""")
command = prompt()
if command == "1":
boss_battle_s()
if command == "2":
if potions > 0:
print("You take a potion bottle")
input()
print("..........")
input()
pHP = playerHP +200
print("Your HP has been refilled to",pHP)
pHP = playerHP
else:
print("You have no potions left!")
input()
boss_battle_s()
def boss_battle_s():
bossdamage = random.randint(80, 220)
bossHP = 4000
bossHP = bossHP - bossdamage
print("Boss HP is now:", bossHP)
input()
if bossHP <= 0:
win()
elif playerHP <= 0:
death()
else:
boss_battle_m()
def battlem():
print("""
1. Attack 3. Run
2. Use potion
""")
command = prompt()
if command == "1":
Attack()
elif command == "2":
Potiondesu()
elif command == "3":
Run()
else:
battlem()
#CURRENT DAMAGE BY THE CURRENT HEALTH
def Attack():
damage = random.randint(120,240) - random.randint(80,120)
currentHP = 0
currentHP -= damage
input()
print("You swing your sword at the enemy!")
print("Inflicted damage:",damage,"enemy HP:",currentHP)
if playerHP <= 0:
death()
elif mobHP <= 0:
win()
else:
battlem()
currentHP=mobHP;
while(currentHP>0):
battlem()
def wepmenu():
print("""
1. Glorion Blades - 200 Mithril
2. Light Sword - 120 Mithril
3. Rapier - 200 Mithril
4. Dagger - 100 Mithril
Supplies Catalogue
Exit Store
""")
print("Which one do you want?")
command = prompt()
if command == "1":
print("The Glorion Blades cost 200 mithril")
input()
if mithril>=200:
print("You buy the blades")
input()
wepmenu()
elif mithril<200:
print("You cannot afford this weapon")
input()
print("Choose another weapon")
wepmenu()
if command == "2":
print("The light sword costs 120 mithril")
input()
if mithril>=150:
print("You buy the sword")
input()
wepmenu()
elif mithril<150:
print("You cannot afford this weapon")
input()
print("Choose another weapon")
wepmenu()
if command == "3":
print("The Rapier costs 200 mithril")
input()
if mithril>=200:
print("You buy the Rapier")
input()
wepmenu()
elif mithril<200:
print("You cannot afford this weapon")
input()
print("Choose another weapon")
wepmenu()
if command == "4":
print("The Dagger costs 100 mithril")
input()
if mithril>=100:
print("You buy the blades")
input()
wepmenu()
elif mithril<100:
print("You cannot afford this weapon")
input()
print("Choose another weapon")
wepmenu()
print("Gotta implement weapon stats")
if command == "Supplies" or "supplies":
supplymenu()
elif command == "Exit":
townone()
def supplymenu():
print("""
1. HP potion - 20 Mithril
2. Large HP Potion - 40 Mithril
Weapons catalogue
Exit Store
""")
print("Which one do you want?")
command = prompt()
if command == "1":
print("The HP Potion costs 20 mithril")
input()
if mithril>=20:
print("You have brought the potion")
input()
supplymenu()
elif mithril<20:
print("You cannot afford this potion")
input()
print("Choose another supply")
input()
supplymenu()
elif command == "2":
print("The Large HP potion costs 40 mithril")
input()
if mithril>=40:
print("You have brought the large potion")
input()
supplymenu()
elif mithril<40:
print("You cannot afford this potion")
input()
print("Choose another supply")
supplymenu()
elif command == "Weapons":
wepmenu()
elif command == "Exit":
townone()
def rest_inn():
print("It will cost 20 mithril to rest at this inn for tonight")
input()
if mithril>=20:
print("You check in")
elif mithril<20:
print("You can't afford to rest here")
input()
print("Kill some monsters for some mithril")
input()
print("You exit the inn")
input()
townone()
print("Your HP has been reset to",HP,"HP")
input()
print("Please press enter to exit the inn")
input()
townone()
def townone():
print("You are at the town of Misgauka")
print("What do you wish to do from here onwards")
print("""
Type Inn to go to the Inn
Type store to go to the store
Type grasslands to go hunt some monsters
Type dungeon to hunt harder monsters
""")
command = prompt()
if command == "Inn":
print("You are now at the Inn, what do you wish to do?")
input()
print("""You can do the following:
Rest
""")
command = prompt()
if command == "Rest":
rest()
if command == "Store":
print("You make your way to the store")
input()
print("Welcome to Tonajta's Weapon and Supplies shop")
input()
print("""You can do the following:
Display Catalogue
Exit store
""")
command = prompt()
if command == "Display" or "display":
print("Open the Weapons Catalogue or the Supplies catalogue")
input()
command = prompt()
if command == "Weapons":
wepmenu()
if command == "Supplies":
supplymenu()
elif command == "Exit":
print("Thanks for coming")
input()
print("Please do visit again")
input
townone()
if command == "Grasslands":
print("All of us have to go into the different pathways I guess")
input()
print("Three paths to each")
input()
print("Alright then, I'll take north, east and then the north pathway")
input()
print("Let's meet back here and gather intel")
input()
print("You make your way to the Grasslands")
input()
print("The pathway goes NORTH")
battles()
print("You will now proceed to the next part of the grasslands")
input()
print(".............")
input()
print("The ground rumbles.....")
input()
print("Another steel-plated guardian appears")
input()
battles()
print("The path is finally clear")
input()
print("You proceed towards the EAST pathway")
input()
print("An approximate of two monsters will spawn here")
input()
print("WHOOSH")
input()
print("A rogue warrior emerges from within the huge bushes")
input()
battles()
print("You run forward")
input()
print("Two more rogue warriors run towards you")
input()
battles()
print("Now remains the last stage of the deadly grasslands")
input()
print("You make the turn")
input()
print("You see the other end of the Grasslands")
input()
print("There is a chair at a high position")
input()
print("Two figures seem to be running towards you")
input()
print("Prepare for combat")
battles()
input()
battles()
input()
print("You seem to have beat the two orcs")
input()
print("Well, seems like it's time")
input()
print("IT's ONE OF THE HACKERS")
input()
print("Fight me, and I take this mask off")
input()
boss_battle()
print("Ahhhhhhhhhhhhhhhhhh")
input()
print("This can't be happening")
input()
print("Now that we're done here..")
input()
print("Show me your face!")
input()
print("Pfff..")
input()
print("TAKES MASK OFF")
input()
print("Oh, so it's you Chaps")
input()
print("You know you won't win right")
input()
print("Even though you defeated me, you can't get past shad....")
input()
print("Who?")
input()
print("NOTHING, now as promised, I'll give you the location of the next town")
input()
print("Where can I find the others in your pathetic group")
input()
print("Huh, you have a big mouth don't you")
input()
print("hehehehehhehhe......")
input()
print("HAHHAHAHHAHAHAHHAHA")
input()
print("A flash of blue light and the player vanishes.........")
input()
print("Well, he's done for")
input()
print("TING TING TING")
input()
print("Huh, what's th..........")
input()
print('{:^80}'.format("SERVER ANNOUNCEMENT"))
time.sleep(2)
print('{:^80}'.format("TOWN OF REPLAUD NOW AVAILABLE TO ALL PLAYERS"))
time.sleep(2)
print('{:^80}'.format("TO REACH, PLEASE CLEAR DUNGEON"))
time.sleep(2)
input()
elif command == "Dungeon":
print("The dungeon cannot be accessed yet")
input()
print("To unlcok the dungeon, you must clear the grasslands")
input()
else:
print("You seem to have entered a wrong command")
input()
print("""Please enter either of these:
1. Inn
2. Store
3. Greenlands
4. Dungeon
""")
townone()
townone()
It's not clear what's causing the error from the code you posted, but from the behavior you describe it sounds like you're not defining mobHP as a global. Here's some example code.
mobHP = 20000
playerHP = 30000
def check_hps():
if mobHP <= 0:
win()
if playerHP <= 0:
lose()
def broken_attack():
attack_value = 100 # how hard you hit
mobHP -= attack_value
check_hps()
def fixed_attack():
global mobHP
attack_value = 100
mobHP -= attack_value
check_hps()
To demonstrate:
>>> mobHP
20000
>>> broken_attack()
>>> mobHP
20000
>>> fixed_attack()
>>> mobHP
19900
>>> fixed_attack()
>>> mobHP
19800
This code is, of course, really difficult to maintain. It is, however, pretty easy to implement. Contrast with:
class Actor(object):
def __init__(self, name, maxHP, min_dmg, max_dmg):
self.name = name
self.maxHP = maxHP
self.currentHP = maxHP
self.roll_dmg = lambda: random.randint(min_dmg, max_dmg)
def attack(self, other, retaliation=False):
other.currentHP -= self.roll_dmg()
if not retaliation:
other.attack(self, retaliation=True)
def run(self, other):
if random.random() >= 0.5:
return True
return False
class Battle(object):
def __init__(self, *actors, location=None):
self.actors = actors
self.location = location
def do_round(self):
for actor in self.actors:
choice, target = self.make_choice(actor)
self.do_choice(choice, target)
yield self.check_battle_over()
def check_battle_over(self):
for actor in self.actors:
if actor.currentHP <= 0:
return actor
return None
def do_choice(self, func, target):
return func(target)
def make_choice(self, actor):
print("1. Attack\n"
"2. Run away\n")
choice = input(">> ")
if choice == '1':
action = actor.attack
elif choice == '2':
action = actor.run
actor_mapping = {num:act for num,act in enumerate(
filter(lambda a: a is not actor), start=1}
print("Target:")
print("\n".join(["{}. {}".format(*target) for target in actor_mapping.items()]))
target = actor_mapping[input(">> ")]
return (action, target)
def start(self):
while True:
loser = do_round()
if loser:
print(loser.name + " is dead!")
return
player = Actor(name="Player", maxHP=30000,
min_dmg=80, max_dmg=200)
monster = Actor(name="Monster", maxHP=20000,
min_dmg=50, max_dmg=100)
battle = Battle(player, monster)
battle.start()

NameError: global name 'has_dynamite' is not defined

I'm new to programming. I'm learning python from here. I am on lesson 36 which says to make a small game. This is the game:
from sys import exit
def you_won():
print """
CONGRATUFUCKINGLATIONS!!!
You won this really easy but kind of cool game.
This is my first game but not the last.
Thanks for playing.
Do you want to start over? Yes or No?
"""
next = raw_input("> ")
if next == "Yes" or "yes":
start()
elif next == "No" or "no":
exit(0)
else:
try_again()
def try_again(function_name):
print "That doesn't make sense, try again."
function_name()
def youre_dead():
print "You died, do you want to start over? Yes or No?"
next = raw_input("> ")
if next == "Yes" or "yes":
start()
elif next == "No" or "no":
exit(0)
else:
try_again()
def main_room():
print """
You enter a grand room with a throne in the back.
Standing right in front of you is the Qurupeco.
He snarls at you and you bare your teeth.
You can:
1 Attack Qurupeco
2 Taunt Qurupeco
3 Run Away
"""
if has_dynamite == True:
print "A Use Dynamite"
if has_sword == True:
print "B Use Sword"
if has_bow == True:
print "C Use Bow"
next = raw_input("> ")
if next == "1":
"You attack the Qurupeco but he stabs you and carves your heart out with a spoon."
youre_dead()
elif next == "2":
"You taunt the Qurupeco and he bites off your legs and lets you bleed to death."
youre_dead()
elif next == "3":
print "You try to run away but the Qurupeco is too fast. He runs you down and eats your entire body."
youre_dead()
elif next == "A" or "a":
print "You throw a stick of dynamite into his mouth and it blows him into tiny marshmallow size pieces."
you_won()
elif next == "B" or "b":
"You slice him squarely in two equal pieces."
you_won()
elif next == "C":
"You shoot him with your bow right between the eyes."
you_won()
def rightdoor_smallway():
print """
You go in the left door and see a lever at at the end of the room.
The flooring looks weird in this room.
You can:
1 Pull Lever
2 Leave
"""
next = raw_input("> ")
if next == "1":
print """
You pull the lever and feel the floor rush from beneath your feet.
You fall for a while and land head first on a giant spike.
"""
youre_dead()
if next == "2":
main_room()
def open_bow_chest():
print "You open the chest and find a bow and some arrows."
print "You take them and leave."
has_bow = True
main_room()
return has_bow
def leftdoor_smallway():
print """
You open the door to your left and see a chest.
You can:
1 Open Chest
2 Leave
"""
next = raw_input("> ")
if next == "1":
open_bow_chest()
elif next == "2":
main_room()
else:
try_again()
def forward_threeway():
print """
You walk forward for a while until you see two doors.
There is one to your right and one to your left.
You can:
1 Go Right
2 Go Left
3 Go Forward
Note: If you go left, you can't go right.
"""
next = raw_input("> ")
if next == "1":
rightdoor_smallway()
elif next == "2":
leftdoor_smallway()
elif next == "3":
main_room()
def three_way2():
forward_threeway()
def reason_meanman():
print """
You try to get the man to leave the damsel alone but he refuses.
When you insist he gets mad and snaps your neck.
"""
youre_dead()
def flirt_damsel():
print """
You flirt with the damsel, one thing leads to another and you end up having sex.
It was great.
Afterwards you tell her to wait for you there and you leave to finish your mission.
"""
three_way2()
def free_damsel():
print "You unchain the damsel, tell her where your king's castle is, and then leave."
three_way2()
def punch_meanman():
print """
You punch the mean man and he falls through a large random spike.
Ouch.
The damsel says thank you and tries her best to be seductive.
You can:
1 Flirt With Her
2 Free Her
3 Leave Her There
"""
next = raw_input("> ")
if next == "1":
flirt_damsel()
elif next == "2":
free_damsel()
elif next == "3":
three_way2()
else:
try_again()
def left_threeway():
print """
You go left for what seems like forever and finally see a door on the right.
You enter the room and see a mean looking man terrorizing a damsel that is chained to a post.
You can:
1 Reason With Mean Man
2 Punch Mean Man
3 Run Away
"""
next = raw_input("> ")
if next == "1":
reason_meanman()
elif next == "2":
punch_meanman()
elif next == "3":
three_way2()
else:
try_again()
def attack_gorilla():
print "You run at the gorilla and he bites your head off."
youre_dead()
def taunt_gorilla():
print """
You taunt the gorilla and he runs at you.
You trip him and he smacks his head into the wall so hard that he dies.
You can:
1 Leave
2 Open Chest
"""
next = raw_input("> ")
if next == "1":
three_way2()
elif next == "2":
print "You open the chest, find a sword, take it, and leave."
has_sword = True
three_way2()
else:
try_again()
return has_sword
def right_threeway():
print """
You go right for what seems like forever and finally find a door.
You enter the room and see a giant gorilla gaurding a chest.
You can:
1 Attack Gorilla
2 Taunt Gorilla
3 Run Away
"""
next = raw_input("> ")
if next == "1":
attack_gorilla()
elif next == "2":
taunt_gorilla()
elif next == "3":
three_way2()
else:
try_again()
def back_threeway():
print """
You walk outside and hear a click sound.
You try to open the door but it is now locked.
You freeze to death.
"""
youre_dead()
def three_way1():
print """
You enter the castle and see long hallways in every direction but behind you.
You can:
1 Go Forward
2 Go Left
3 Go Right
4 Go Back
Note: You can only pick one of the last three.
"""
next = raw_input("> ")
if next == "1":
forward_threeway()
elif next == "2":
left_threeway()
elif next == "3":
right_threeway()
elif next == "4":
back_threeway()
else:
try_again()
def go_inside():
print "You go back to the entrance, open the door, and go inside."
three_way1()
def poison_chest():
print "You struggle with the chest for a minute and finally figure out the mechanism, but, unfortunately, a poisonous gas is released and you die in agony."
youre_dead()
def outside_left():
print """
You go to the right and see a treasure chest three meters forward.
You can:
1 Go Inside
2 Open Chest
"""
next = raw_input("> ")
if next == "1":
turnback_outside()
elif next == "2":
poison_chest()
else:
try_again(outside_left)
def dynamite_inside():
print "You take the dynamite, it may be useful."
has_dynamite = True
go_inside()
return has_dynamite
def outside_right():
print """
You go left and see a stick of dynamite laying on the ground.
You can:
1 Go inside
2 Take Dynamite
"""
next = raw_input("> ")
if next == "1":
go_inside()
elif next == "2":
dynamite_inside()
else:
try_again(outside_right)
def start():
print """
You are a knight in shining armor, you lost your sword on the way here.
You have come to destroy the evil Qurupeco.
You are at the cold entrance to the Qurupeco's castle.
To the right of the entrance is a sign that reads: "Enter at your own risk!"
The walls are made of extremely tough stone.
You can:
1 Enter Castle
2 Go Left
3 Go Right
What do you do?
Note: You can't go left and right.
Note: Enter numbers when you're asked what you want to do.
"""
has_dynamite = False
has_sword = False
has_bow = False
next = raw_input("> ")
if next == "1":
three_way1()
elif next == "2":
outside_left()
elif next == "3":
outside_right()
else:
try_again(start)
return has_dynamite, has_sword, has_bow
start()
This is me playing the game and getting an error that I cant figure out.
jacob#HP-DX2450:~/Documents$ python ex36.py
You are a knight in shining armor, you lost your sword on the way here.
You have come to destroy the evil Qurupeco.
You are at the cold entrance to the Qurupeco's castle.
To the right of the entrance is a sign that reads: "Enter at your own risk!"
The walls are made of extremely tough stone.
You can:
1 Enter Castle
2 Go Left
3 Go Right
What do you do?
Note: You can't go left and right.
Note: Enter numbers when you're asked what you want to do.
> 3
You go left and see a stick of dynamite laying on the ground.
You can:
1 Go inside
2 Take Dynamite
> 2
You take the dynamite, it may be useful.
You go back to the entrance, open the door, and go inside.
You enter the castle and see long hallways in every direction but behind you.
You can:
1 Go Forward
2 Go Left
3 Go Right
4 Go Back
Note: You can only pick one of the last three.
> 1
You walk forward for a while until you see two doors.
There is one to your right and one to your left.
You can:
1 Go Right
2 Go Left
3 Go Forward
Note: If you go left, you can't go right.
> 3
You enter a grand room with a throne in the back.
Standing right in front of you is the Qurupeco.
He snarls at you and you bare your teeth.
You can:
1 Attack Qurupeco
2 Taunt Qurupeco
3 Run Away
Traceback (most recent call last):
File "ex36.py", line 368, in <module>
start()
File "ex36.py", line 362, in start
outside_right()
File "ex36.py", line 331, in outside_right
dynamite_inside()
File "ex36.py", line 316, in dynamite_inside
go_inside()
File "ex36.py", line 290, in go_inside
three_way1()
File "ex36.py", line 278, in three_way1
forward_threeway()
File "ex36.py", line 140, in forward_threeway
main_room()
File "ex36.py", line 47, in main_room
if has_dynamite == True:
NameError: global name 'has_dynamite' is not defined
jacob#HP-DX2450:~/Documents$
Any ideas?
The problem is arising due to
variable scope
You can check this question as well to clear your doubt regarding global or local scope:-
Python global/local variables
The variable
has_dynamite
is defined only inside the
start()
function. Therefore, it has only a local scope, to make it global define has_dynamite outside any functions and write your functions like this
def start():
global has_dynamite
Do this for all of the functions which use has_dynamite variable.
You can also pass the has_dynamite variable as a parameter to the function. ie instead of typing the above mentioned code, you can type
start(has_dynamite)
while calling the function, but be sure you include this parameter in the function definition also, otherwise it will show you an error
Here is the corrected code:-
from sys import exit
has_dynamite = True
has_sword = True
has_bow = True
def you_won():
print """
CONGRATUFUCKINGLATIONS!!!
You won this really easy but kind of cool game.
This is my first game but not the last.
Thanks for playing.
Do you want to start over? Yes or No?
"""
next = raw_input("> ")
if next == "Yes" or "yes":
start()
elif next == "No" or "no":
exit(0)
else:
try_again()
def try_again(function_name):
print "That doesn't make sense, try again."
function_name()
def youre_dead():
print "You died, do you want to start over? Yes or No?"
next = raw_input("> ")
if next == "Yes" or "yes":
start()
elif next == "No" or "no":
exit(0)
else:
try_again()
def main_room():
global has_dynamite
global has_sword
global has_bow
print """
You enter a grand room with a throne in the back.
Standing right in front of you is the Qurupeco.
He snarls at you and you bare your teeth.
You can:
1 Attack Qurupeco
2 Taunt Qurupeco
3 Run Away
"""
if has_dynamite == True:
print "A Use Dynamite"
if has_sword == True:
print "B Use Sword"
if has_bow == True:
print "C Use Bow"
next = raw_input("> ")
if next == "1":
"You attack the Qurupeco but he stabs you and carves your heart out with a spoon."
youre_dead()
elif next == "2":
"You taunt the Qurupeco and he bites off your legs and lets you bleed to death."
youre_dead()
elif next == "3":
print "You try to run away but the Qurupeco is too fast. He runs you down and eats your entire body."
youre_dead()
elif next == "A" or "a":
print "You throw a stick of dynamite into his mouth and it blows him into tiny marshmallow size pieces."
you_won()
elif next == "B" or "b":
"You slice him squarely in two equal pieces."
you_won()
elif next == "C":
"You shoot him with your bow right between the eyes."
you_won()
def rightdoor_smallway():
print """
You go in the left door and see a lever at at the end of the room.
The flooring looks weird in this room.
You can:
1 Pull Lever
2 Leave
"""
next = raw_input("> ")
if next == "1":
print """
You pull the lever and feel the floor rush from beneath your feet.
You fall for a while and land head first on a giant spike.
"""
youre_dead()
if next == "2":
main_room()
def open_bow_chest():
global has_bow
print "You open the chest and find a bow and some arrows."
print "You take them and leave."
has_bow = True
main_room()
return has_bow
def leftdoor_smallway():
print """
You open the door to your left and see a chest.
You can:
1 Open Chest
2 Leave
"""
next = raw_input("> ")
if next == "1":
open_bow_chest()
elif next == "2":
main_room()
else:
try_again()
def forward_threeway():
print """
You walk forward for a while until you see two doors.
There is one to your right and one to your left.
You can:
1 Go Right
2 Go Left
3 Go Forward
Note: If you go left, you can't go right.
"""
next = raw_input("> ")
if next == "1":
rightdoor_smallway()
elif next == "2":
leftdoor_smallway()
elif next == "3":
main_room()
def three_way2():
forward_threeway()
def reason_meanman():
print """
You try to get the man to leave the damsel alone but he refuses.
When you insist he gets mad and snaps your neck.
"""
youre_dead()
def flirt_damsel():
print """
You flirt with the damsel, one thing leads to another and you end up having sex.
It was great.
Afterwards you tell her to wait for you there and you leave to finish your mission.
"""
three_way2()
def free_damsel():
print "You unchain the damsel, tell her where your king's castle is, and then leave."
three_way2()
def punch_meanman():
print """
You punch the mean man and he falls through a large random spike.
Ouch.
The damsel says thank you and tries her best to be seductive.
You can:
1 Flirt With Her
2 Free Her
3 Leave Her There
"""
next = raw_input("> ")
if next == "1":
flirt_damsel()
elif next == "2":
free_damsel()
elif next == "3":
three_way2()
else:
try_again()
def left_threeway():
print """
You go left for what seems like forever and finally see a door on the right.
You enter the room and see a mean looking man terrorizing a damsel that is chained to a post.
You can:
1 Reason With Mean Man
2 Punch Mean Man
3 Run Away
"""
next = raw_input("> ")
if next == "1":
reason_meanman()
elif next == "2":
punch_meanman()
elif next == "3":
three_way2()
else:
try_again()
def attack_gorilla():
print "You run at the gorilla and he bites your head off."
youre_dead()
def taunt_gorilla():
print """
You taunt the gorilla and he runs at you.
You trip him and he smacks his head into the wall so hard that he dies.
You can:
1 Leave
2 Open Chest
"""
next = raw_input("> ")
if next == "1":
three_way2()
elif next == "2":
print "You open the chest, find a sword, take it, and leave."
has_sword = True
three_way2()
else:
try_again()
return has_sword
def right_threeway():
print """
You go right for what seems like forever and finally find a door.
You enter the room and see a giant gorilla gaurding a chest.
You can:
1 Attack Gorilla
2 Taunt Gorilla
3 Run Away
"""
next = raw_input("> ")
if next == "1":
attack_gorilla()
elif next == "2":
taunt_gorilla()
elif next == "3":
three_way2()
else:
try_again()
def back_threeway():
print """
You walk outside and hear a click sound.
You try to open the door but it is now locked.
You freeze to death.
"""
youre_dead()
def three_way1():
print """
You enter the castle and see long hallways in every direction but behind you.
You can:
1 Go Forward
2 Go Left
3 Go Right
4 Go Back
Note: You can only pick one of the last three.
"""
next = raw_input("> ")
if next == "1":
forward_threeway()
elif next == "2":
left_threeway()
elif next == "3":
right_threeway()
elif next == "4":
back_threeway()
else:
try_again()
def go_inside():
print "You go back to the entrance, open the door, and go inside."
three_way1()
def poison_chest():
print "You struggle with the chest for a minute and finally figure out the mechanism, but, unfortunately, a poisonous gas is released and you die in agony."
youre_dead()
def outside_left():
print """
You go to the right and see a treasure chest three meters forward.
You can:
1 Go Inside
2 Open Chest
"""
next = raw_input("> ")
if next == "1":
turnback_outside()
elif next == "2":
poison_chest()
else:
try_again(outside_left)
def dynamite_inside():
global has_dynamite
print "You take the dynamite, it may be useful."
has_dynamite = True
go_inside()
return has_dynamite
def outside_right():
print """
You go left and see a stick of dynamite laying on the ground.
You can:
1 Go inside
2 Take Dynamite
"""
next = raw_input("> ")
if next == "1":
go_inside()
elif next == "2":
dynamite_inside()
else:
try_again(outside_right)
def start():
global has_dynamite
global has_sword
global has_bow
print """
You are a knight in shining armor, you lost your sword on the way here.
You have come to destroy the evil Qurupeco.
You are at the cold entrance to the Qurupeco's castle.
To the right of the entrance is a sign that reads: "Enter at your own risk!"
The walls are made of extremely tough stone.
You can:
1 Enter Castle
2 Go Left
3 Go Right
What do you do?
Note: You can't go left and right.
Note: Enter numbers when you're asked what you want to do.
"""
has_dynamite = False
has_sword = False
has_bow = False
next = raw_input("> ")
if next == "1":
three_way1()
elif next == "2":
outside_left()
elif next == "3":
outside_right()
else:
try_again(start)
return has_dynamite, has_sword, has_bow
start()
I hope this helps
has_dynamite is not global but local variable. It exists only in start()
Put it outside all functions to make it global.
has_dynamite = False
has_sword = False
has_bow = False
start()
Now you can get value of has_dynamite in any function
But if you need to change global value you have to use global keyword
def dynamite_inside():
global has_dynamite
print "You take the dynamite, it may be useful."
has_dynamite = True
go_inside()
# return has_dynamite # unusable line

Categories