尝试修改全局变量时出现“ NameError:名称未定义”

尝试使用功能修改脚本中的变量时遇到问题。

def damage(x):
    """ This function will determine the amount of damage you will take """
    """ hit_c is the chance the enemy has to hit you """
    from random import randint

    global User_HP
    global Enemy_HP

    hit_c = randint(1,5)
    User_damage = randint(1,4)

    if hit_c >= 2:
        Enemy_HP -= User_damage
        lcd_print(textscroll(f"You dealt {User_damage} damage!"))
        lcd_clear()
        lcd_print(textscroll(f"The enemy has {Enemy_HP} HP")
        sleep(1)

    elif hit_c == 1:
            lcd_print("You missed!")

    if Enemy_HP <= 0:
        pass

    else:
        hit_c = randint(1,5)
        Enemy_damage = randint(1,3)

        if hit_c >= 2:
            User_HP -= Enemy_damage
            lcd_print(textscroll(f"You took {Enemy_damage} damage!"))
            lcd_clear()
            lcd_print(User_HP)

        elif hit_c == 1:
            lcd_print(textscroll("The enemy missed!"))

当我尝试在此行中修改全局变量Enemy_HP时,该函数将不会读取它。

Enemy_HP -= User_damage

注意,我在脚本开始处定义了Enemy_HP = 10。

非常感谢帮助!

错误-

File "D:\Desktop\Python Scripts\Lab Project\Lab_Project_Functions.py", line 41, in damage
    Enemy_HP -= User_damage
NameError: name 'Enemy_HP' is not defined`
评论