Python function doesn't update value of variable - python

def Act(enemy, pokemon, enemyHP, enemyType):
num = round(random.uniform(0.95, 1.75), 2)
print(MoveList)
Move1 = input("Choose your attack! Input a number from 1-4, depending on the order of your moves. Input 5 to view everyone's stats! \n")
if Move1 == "1":
Move1 = str(MoveList[0])
attacked = True
dmg = 10 * num
Move1 = MoveList[0]
print(pokemon + " used " + Move1 + "! \n")
enemyHP -= dmg
print("It dealt " + str(dmg) + " damage to " + enemy + "! \n")
print(enemy + " is now at " + str(enemyHP) + " HP!")
return enemyHP
while battling == true:
Act(RivalPKMN, starter, RivalHP, RivalType)
This function takes an input from the player, does a move, and deducts HP from the function parameter enemyHP (similar to Pokemon). However, after doing an input again, the enemyHP value does not update to what it was after the first move.
I tried using return statements but I'm not really sure what or where the problem even is.
Here's an example of how it looks:
Litten used Scratch!
It dealt 10.5 damage to Quaxly!
Quaxly's HP is now 44.5!
The second time I run the function it inputs the exact same thing without updating the HP value to what it was after the first move was done.

This is a simple beginner mistake. just add global [variable name] at the start of the function and it should work.

Related

Can't Make Code Detect whose turn it is in Python IDLE

My friend and I are trying to code the "21" game into Python, where you play against a random thingy and you take in turns adding numbers (from 1-4) to a score and if its 21 or above when its your turn, you lose.
but we can't figure out how to make it detect who's turn it was when it reaches 21
Here's my code so far:
import random
import time
carryOn = True
counter = 0
print("First to 21 or above LOSES\n \n")
while carryOn == True:
user = input("Please enter any number from 1 – 4")
print("You Chose " + user)
counter = counter + int(user)
print("The new Total is " + str(counter) + "\n")
user == 0
time.sleep(3)
computer = random.randint(1,4)
print("The Computer Rolled a " + str(computer))
counter = counter + int(computer)
print("The new Total is " + str(counter) + "\n")
if counter == 21:
carryOn == False
First your code does not detect when the score is 21, because if statement is not inside while loop and because you are comparing carryOn with False, but not setting it to False. Also if statement should check if counter is more or equal than 21, because you can jump over it (for example score was 20 and then 24).
And you need to check counter after each turn, not after every two turns, because game might end after user's turn. To end loop in the middle you can use break or continue. I prefer continue, so it ends up like this
import random
import time
carryOn = True
counter = 0
print("First to 21 or above LOOSES\n \n")
while carryOn:
user = input("Please enter any number from 1 – 4")
print("You Chose " + user)
counter = counter + int(user)
print("The new Total is " + str(counter) + "\n")
if counter >= 21:
print('User lost')
carryOn = False
continue
computer = random.randint(1,4)
print("The Computer Rolled a " + str(computer))
counter = counter + int(computer)
print("The new Total is " + str(counter) + "\n")
if counter >= 21:
print('Computer lost')
carryOn = False

Can someone please explain to me why the 'health' var is not updated when calling the updateGame() func

Been looking online for some answers, however it's still unclear to me why the 'health' var is not updated when calling the getDamage() func
I'm on my first few miles learning python
health = 200.0
maxHealth = 200
healthDashes = 20
dashConvert = int(maxHealth/healthDashes)
currentDashes = int(health/dashConvert)
remainingHealth = healthDashes - currentDashes
healthDisplay = '-' * currentDashes
remainingDisplay = ' ' * remainingHealth
percent = str(int((health/maxHealth)*100)) + "%"
gameOver = False
def updateGame():
print(chr(27) + "[2J")
print (30 * '-')
print("")
print(" |" + healthDisplay + remainingDisplay + "|")
print(" health " + percent)
print ("")
print (30 * '-')
print("")
def getDamage():
global health
health = 10
while gameOver == False:
answer = raw_input("> ").lower()
if answer == "help":
print("")
print(" you can use the following commands: h, i, q, d")
print("")
elif answer == "q":
print("\n")
print("Game Over")
print("")
break
elif answer == "h":
updateGame()
elif answer == "d":
getDamage()
else:
print(""" not a valid command, see "help" """)
Is there anything I can do to properly update the "health" var and disply a reduced health the next time I call the getDamage() func?
Basically what I'm trying to achieve is a text-based game to run in a while loop and have different functions to update a primary function (updateGame) that display relevant info about the player's state like health, inventory items.
The logic I'm trying to implement is:
have getDamage() reduce the health var and then display the newly change variable with updateGame()
Many thanks
health will change to 10 when you call getDamage() but healthDisplay, remainingDisplay and percent are set at the first of script and won't change everytime that healt global variable is changed. so you must change them in updateGame() function everytime it's called. Also i guess health = 10 must change to health -= 10!
health = 200.0
maxHealth = 200
healthDashes = 20
gameOver = False
def updateGame():
dashConvert = int(maxHealth/healthDashes)
currentDashes = int(health/dashConvert)
remainingHealth = healthDashes - currentDashes
healthDisplay = '-' * currentDashes
remainingDisplay = ' ' * remainingHealth
percent = str(int((health/maxHealth)*100)) + "%"
print(chr(27) + "[2J")
print (30 * '-')
print("")
print(" |" + healthDisplay + remainingDisplay + "|")
print(" health " + percent)
print ("")
print (30 * '-')
print("")
def getDamage():
global health
health -= 10
while gameOver == False:
answer = input("> ").lower()
if answer == "help":
print("")
print(" you can use the following commands: h, i, q, d")
print("")
elif answer == "q":
print("\n")
print("Game Over")
print("")
break
elif answer == "h":
updateGame()
elif answer == "d":
getDamage()
else:
print(""" not a valid command, see "help" """)
Inside the updateGame function, you never make reference to the global variable health. If you want health to change inside the function, you will need to access it.
This means you should have something like:
def updateGame():
global health
health = updatedHEALTH
...
Then it should change each time you call the function

Python: local variable referenced before assigment

I'm very new to python (~1 wk). I got this error when trying to run this code, intended to be a simple game where you guess heads or tails and it keeps track of your score. Is there any way I can avoid this error? I get the error for the "attempts" variable when I run attempts += 1, but I assume I'd get it for "score" too when I do the same.
import random
coin = ['heads', 'tails']
score = 0
attempts = 0
def coin_flip():
print("Heads or tails?")
guess = input()
result = random.choice(coin)
print("Your guess: " + guess)
print("Result: " + result)
attempts += 1
if result == guess:
print('You guessed correctly!')
score += 1
else:
print('Your guess was incorrect.')
percentCorrect = str((score / attempts) * 100) + '%'
print("You have " + str(score) + " correct guesses in " + str(attempts) + ' attempts.')
print("Accuracy: " + percentCorrect)
print('Do you want to play again?')
if input() == 'y' or 'yes':
return coin_flip()
else:
quit()
coin_flip()
import random
coin = ['heads', 'tails']
score = 0
attempts = 0
def coin_flip():
global attempts
global score
print("Heads or tails?")
guess = input()
result = random.choice(coin)
print("Your guess: " + guess)
print("Result: " + result)
attempts += 1
if result == guess:
print('You guessed correctly!')
score += 1
else:
print('Your guess was incorrect.')
percentCorrect = str((score / attempts) * 100) + '%'
print("You have " + str(score) + " correct guesses in " + str(attempts) + ' attempts.')
print("Accuracy: " + percentCorrect)
print('Do you want to play again?')
if input() == 'y' or 'yes':
return coin_flip()
else:
quit()
coin_flip()
What was missing:
global attempts
global score
This is an issue with scoping. Either put the word global in front of attemps and score, or create a class (which would not be ideal for what I assume you're doing).

Why is it that the list variables in this code gets values in them backwards? HP is the last assigned variable despite being there first in the list

I'm making a simple program (I am a beginner at python) where I fight a monster with random assigned values. I used 2 lists with 4 variables each depicting hp atk def and spd. They get assigned a random number of 10 to 15 and get multiplied by 2. I don't really know what I am doing wrong here.
import random
monsters = ["slime","goblin","troll","dryad","bard","clown"]
hp,atk,dfn,spd = 0,0,0,0
mhp,matk,mdfn,mspd = 0,0,0,0
stats = [hp,atk,dfn,spd]
mstats = [hp,atk,dfn,spd]
damage = 0
defend = 0
action = "none"
name = input()
print("Your name is " + name + ", time to battle!")
for x in stats:
stats[x] = random.randint(10,15) * 2
print("Your stats(hp/a/d/s): " + str(stats[x]))
for y in mstats:
mstats[y] = random.randint(10,15) * 2
print("Monster stats(hp/a/d/s): " + str(mstats[y]))
while stats[hp] > 0 or mstats[hp] > 0:
print("What will you do? 1 for attack, 2 for defend, others to give up")
action = input()
if action == "1":
damage = stats[atk] / 2 + random.randint(1,5)
mstats[hp] = mstats[hp] - damage
print("You slash the monster for " + str(damage) + " damage!" )
print("Monster HP: " + str(mstats[hp]))
damage = mstats[atk] / 2
stats[hp] = stats[hp] - damage
print("The monster slashes you for " + str(damage) + " damage!")
print("Your HP: " + str(stats[hp]))
if action == "2":
damage = mstats[atk] / 2 - random.randint(3,5)
if damage > 0:
stats[hp] = stats[hp] - damage
print("The monster slashes you for " + str(damage) + " damage!")
print("Your HP: " + str(stats[hp]))
if action != "1" and action != "2":
stats[hp] = 0
if stats[hp] < 0 or stats[hp] == 0:
print("You lose!")
if mstats[hp] < 0:
print("You win!")
Hopefully this code isn't a mess, I thank you all in advance if extra corrections can be given.

use of global, but still not recognized in Python function

I was making a game where you need to fight monsters, just to practice my coding, when I got an error I couldn't understand. Here is the code, and the error I received:
Note: I changed it to the full code so you could see everything. Sorry about how long it is.
import random
import time
player_level = 1
player_HP = 4
player_mana = 2
player_action = "Placeholder"
entity_list = ["Nymph", "Komodo", "Free Soul"]
current_monster_level = player_level
current_monster_HP = random.randrange(current_monster_level, (current_monster_level * 3) + 1)
monster_name = entity_list[random.randrange(0, 3)]
def spawn_monster(level):
import random
global current_monster_HP
global monster_name
current_monster_HP = random.randrange(level, level * 3)
monster_name = entity_list[random.randrange(0, 3)]
print("A ", monster_name, "attacks you!")
print("The ", monster_name, " has ", current_monster_HP, " HP!")
def attack(level):
import random
global monster_name
global current_monster_HP
damage = random.randrange(level, level + 4)
current_monster_HP = current_monster_HP - damage
if damage == 0:
print("You missed! No damage done! ", monster_name, "'s HP is ", current_monster_HP, " !")
elif damage > current_monster_HP:
damage = current_monster_HP
print("You did ", damage, " damage! The ", monster_name, " was defeated!")
else:
print("You did ", damage, " damage. The enemy's HP is now ", current_monster_HP, "!")
def spell(level):
global player_mana
global player_HP
player_mana = player_mana - 2
player_HP = player_HP + level
print("A spell is cast, and you gain ", level, "HP!")
def monster_retaliate(level):
import random
global player_HP
global monster_name
global current_monster_HP
damage = random.randrange(level, level + 2)
player_HP = player_HP - damage
print("The ", monster_name, " attacked you, dealing ", damage, " damage!")
if damage == 0:
print("The enemy missed! No damage done! Your HP is ", player_HP, "!")
elif damage > current_monster_HP:
damage = current_monster_HP
else:
print("the ", monster_name, " did ", damage, " damage. Your HP is now ", player_HP, "!")
print("xxxxxxxxxxxxx")
print("xxxxxxxxxxxxx")
print("x Blind RPG x")
print("xxxxxxxxxxxxx")
print("xxxxxxxxxxxxx")
print("\n")
begin = input("Start a new game?").lower()
if begin == "yes":
print("Your tale starts when your memory does. You can't remember anything!")
time.sleep(1)
print("You wake up in an empty field, and you think you see a shadowy figure.")
time.sleep(1)
print("It slips away into the faraway trees lining the grassy field, or does it?")
time.sleep(1)
print("You stand up.")
time.sleep(1)
print("You decide to go over to where the shadow left the field.")
time.sleep(1)
print("On the ground, you see a small sword. You pick it up.")
time.sleep(1)
print("Suddenly, something jumps out at you from behind a tree.")
time.sleep(1)
spawn_monster(1)
while current_monster_HP > 0:
player_action = input("What do you do?").lower()
if player_action == "attack":
attack(player_level)
time.sleep(2)
if current_monster_HP > 0:
monster_retaliate(1)
else:
break
elif player_action == "cast spell":
spell(player_level)
time.sleep(2)
monster_retaliate(1)
else:
print("The enemy attacked you as you stood unmoving!")
monster_retaliate(1)
if current_monster_HP <= 0:
print("You win! Apparently you remember how to fight!")
break
if player_HP <= 0:
print("You died! If only you had remembered how to fight...")
break
else:
print("Then why did you open the game?")
The attack() function works, and the spell() function both work, it is only the monster_retaliate() function that is causing trouble. The Error code is:
File "/Users/(Replacing my name for privacy)/Documents/Blind RPG.py", line 57, in monster_retaliate
player_HP = player_HP - damage
NameError: name 'player_HP' is not defined
I thought this was funny, seeing as I used the global keyword
global doesn't actually create a variable; it just indicates that the name should be defined in the global scope, and to modify that (instead of a local variable) when you assign to it. You still need to give it a value before you try to access it.

Categories