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()
>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.