user3133346
user3133346

Reputation: 1

Can't fix the bug in my python game

I wrote this code

hp0 = 100
atk0 = 30
hp1 = 100
atk1 = 5
print("Action? (attack, heal, nothing):")
act = input("> ")
while hp0 > 0 and hp1 > 0:
    if act == "attack":
        hp1 = hp1 - atk0
        if hp1 <= 0:
            print("You won!")
        print("{} DMG".format(atk0)
              )
    if act == "heal":
        hp0 = hp0 + 15
        print("+15 HP")
    else:
        print("...")
    print("Enemy attacked you! -{} hp".format(atk1))
    hp0 = hp0 - atk1
    print("{}HP player".format(hp0))
    print("{}HP enemy".format(hp1))
    print("Action? (attack, heal, nothing):")
    act = input("> ")
if hp0 > 0:
    if hp1 <= 0:
        print("You won!")
if hp1 > 0:
    if hp0 <= 0:
        print("You lose")

It's a battle between you (with hp0 and atk0) and "a monster" (with hp1 and atk1). when I keep attacking, there is a moment when enemy's life (hp1) is -20 and it lets me decide one more action before it tells me I won.

Same thing happens when I decide to do nothing and my health point (hp0) become 0 but it let me one more action, and I can decide to heal and game continues.

How can I fix this?

Upvotes: 0

Views: 61

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121476

Move asking for the next action to the top of the loop:

hp0 = 100
atk0 = 30
hp1 = 100
atk1 = 5

while hp0 > 0 and hp1 > 0:
    print("Action? (attack, heal, nothing):")
    act = input("> ")
    if act == "attack":
        hp1 = hp1 - atk0
        if hp1 <= 0:
            print("You won!")
        print("{} DMG".format(atk0)
              )
    if act == "heal":
        hp0 = hp0 + 15
        print("+15 HP")
    else:
        print("...")
    print("Enemy attacked you! -{} hp".format(atk1))
    hp0 = hp0 - atk1
    print("{}HP player".format(hp0))
    print("{}HP enemy".format(hp1))

and remove the other print("Action? ...") and input("> ") lines.

Upvotes: 1

Related Questions