[SOLVED] How can i take health off a variable in my game

Issue

This Content is from Stack Overflow. Question asked by JAYAJYAYA

so i’m wanting to be able to display the user’s health after they’ve been kicked, punched or slapped, but it doesn’t keep it for some reason. I go to display it on a separate line, but it just says “100”. Here’s my code:

#random attack damage
player1Health = 100
player2Health = 100
punch = random.randint(5, 20)
kick = random.randint(5, 20)
slap = random.randint(5, 20)

#Checking if player chooses any of the attackTypes
player2HealthSlap = player2Health - slap
player2HealthPunch = player2Health - punch
player2HealthKick = player2Health - kick
if punch:
    puchAttack = print(
        f"Ouchh! {player1} just punched {player2}, and reduced their health amount to {player2HealthPunch}"
    )

elif kick:
    kickAttack = print(
        f"Wow! {player1} just kicked {player2}, reducing their health amount to {player2HealthKick}"
    )

elif slap:
    slapAttack = print(
        f"Oh no, that seemed to harm {player2} badly. Their health has reduced to       {player2HealthSlap}"
    )

I want to be able to call that variable, and have the amount of health player 1 did to player 2.



Solution

You never change player2Health. Instead of storing player2HealthSlap etc. in separate variables, you could

if punch:
    player2Health -= random.randint(5, 20) # subtract some HP from total
    print(f"[...] and reduced their health amount to {player2Health}")


This Question was asked in StackOverflow by JAYAJYAYA and Answered by fsimonjetz It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?