Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

trouble with running combat/health function

I tried to create a combat function but its not working.

It’s supposed to take away 10 from the enemy health when you input one but it doesn’t. I’ve tried taking the values out of the function but it just says UnboundLocalError

def combat():
    global hp
    hp = 100
    global p
    p = 5
    global ehp
    ehp = 100
    global at
    at = 10
    global hg
    hg = 20
    print('player health ' + str(hp))
    print('enemy health ' + str(ehp))
    print('1 attack')
    print('2 heal')
    m = int(input())
    if m == 1:
        ehp = ehp - 10
        combat()
    if m == 2:
        p = p - at
        hp = hp + hg
        combat()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Keep the global declarations, but move the assignment outside the function:

hp = 100
p = 5
ehp = 100
at = 10
hg = 20

def combat():
    global hp
    global p
    global ehp
    global at
    global hg
    print('player health ' + str(hp))
    print('enemy health ' + str(ehp))
    print('1 attack')
    print('2 heal')
    m = int(input())
    if m == 1:
        ehp = ehp - 10
        combat()
    if m == 2:
        p = p - at
        hp = hp + hg
        combat()

combat()

Note that you can replace this recursive function with a simpler while loop. This way you can skip the global declarations and it won’t fail after 1000 turns due to the maximum recursion depth.

hp = 100
p = 5
ehp = 100
at = 10
hg = 20

# You can also stop when someone's HP reaches 0, for example
while True:
    print('player health ' + str(hp))
    print('enemy health ' + str(ehp))
    print('1 attack')
    print('2 heal')
    m = int(input())
    if m == 1:
        ehp = ehp - 10
    elif m == 2:
        p = p - at
        hp = hp + hg

I also suggest using more descriptive names, like enemy_hp and healing_points, otherwise you’ll hate yourself next time you try to read the code and can’t remember what p = p - at is supposed to do.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading