«NameError: имя не определено» при попытке изменить глобальную переменную - PullRequest
0 голосов
/ 09 апреля 2020

У меня проблема при попытке изменить переменную в моем скрипте с помощью функции.

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`

РЕДАКТИРОВАТЬ: Вот полный код, извините за то, что не включил это ранее, я также импортирую несколько функций

from time import sleep
from random import randint
from operator import itemgetter
from engi1020.arduino import *

User_HP = 10
Enemy_HP = 10


wait_1 = True
def loading(wait_time):
    if wait_1 == True:
        sleep(1)
        lcd_clear()
        lcd_print('.')
        sleep(1)
        lcd_clear()
        lcd_print('..')
        sleep(1)
        lcd_clear()
        lcd_print('...')
        sleep(1)
        lcd_clear()
        lcd_print('.')
        sleep(1)
        lcd_clear()
        lcd_print('..')
        sleep(1)
        lcd_clear()
        lcd_print('...')
        sleep(1)
        lcd_clear()

inventory = []

from Lab_Project_Functions import *

#Get some basic gameplay information
lcd_print("starting the game")
lcd_clear()
loading(wait_1)

lcd_print(textscroll("Hello!, What speed would you like the dialogue to play at? ('slow, normal, fast')"))
Dia_Spd = input()
if Dia_Spd == "slow":
    DiaSpd = 4
elif Dia_Spd == "normal":
    DiaSpd = 3
elif Dia_Spd == "fast":
    DiaSpd = 2
elif Dia_Spd == "test":
    DiaSpd = 0

lcd_clear()
lcd_print()
loading(wait_1)
'''
name = input("What is your name?")
class_ = "Knight"

sleep(1)
class_ = input("Which class is befitting you young adventurer?"
                " A noble 'Knight'?"
                " A Studious 'Wizard'?"
                " Or a Mystifying 'Warlock'?")
'''

loading(wait_1)

#lcd_print(f"What ho {class_} {name}, welcome to the game!!")
lcd_print(textscroll("What ho brave knight, welcome to the game!!"))
sleep(DiaSpd)
lcd_clear()

lcd_print(textscroll("Let's start with a some basics"))
sleep(DiaSpd)
lcd_clear()
#Start by creating a basic combat system.

lcd_print(textscroll("An enemy approaches you! Learn to fight!"))
sleep(DiaSpd)
lcd_clear()

#Create more combat elements.

while User_HP > 0:
    lcd_print(textscroll("Pick a fighting option."))
    lcd_print("FIGHT--ITEM--DEF")
    fight_option = input()

    if fight_option == 'FIGHT' or 'fight' or 'Fight':
        damage(1)

    elif fight_option == 'ITEM' or 'item' or 'Item':
        item_pickup(1)

    else:
        defend(1)

    if Enemy_HP <= 0:
        lcd_print(textscroll("THE ENEMY WAS SLAIN!"))
        break

    sleep(DiaSpd)

lcd_print(textscroll("Good job you're learning the basics!"))
sleep(DiaSpd)
lcd_print(textscroll("To reward you for your efforts, here is an item that the enemy dropped!"))
sleep(DiaSpd)
item_pickup(1)

#remember to redefine enemy hp before next fight

lcd_print(textscroll("Hi ho yee noble knight, welcome to your humble abode. You can perform all sorts of actions here."))
sleep(DiaSpd)
lcd_clear()
lcd_print(textscroll("What would you like to do?"))
sleep(DiaSpd)
lcd_clear()
lcd_print(textscroll("Look through inventory----Rest (Heal)----Go adventuring"))
home_option = input() #change this to accept input from button & joystick

while True:
    if home_option == 1:
        pass
    if home_option == 2:
        pass
    if home_option == 3:
        pass

отсюда импортируются функции

from engi1020.arduino import *

#Looting // Item Pickup Function def item_pickup(enemy_num):
    """ This Function will determine the items the user picks up """
    '''
    enemy_num is the variable deciding which enemy you are fighting
    '''
    from random import randint
    rand_item = randint(1,4)
    global inventory

    if enemy_num == 1:
        if rand_item <= 3:
            inventory.append('IRON_SWORD')
            print(textscroll("You picked up the IRON SWORD!"))

        elif rand_item == 4:
            inventory.append('STEELY_VENGANCE')
            lcd_print(textscroll("You found a rare item! 'STEELY VENGANCE' was added to your inventory!"))
        else:
            'no item found'
    if enemy_num == 2:
        pass

#Combat Function 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!"))

#Item Select Function def item_select(item_number):
    from operator import itemgetter

    while True:
        lcd_print(textscroll("What item would you like to use?"))
        lcd_clear()
        sleep(1)
        lcd_print(textscroll("note you need to select items numerically, i.e. 0, 1, 2, 3,...,etc. "))
        lcd_clear()
        sleep(1)
        lcd_print(textscroll(inventory))
        item_choice = int(input())
        lcd_clear()
        lcd_print("Which item?:")
        num_items = len(inventory)
        if item_choice < num_items:
            item = itemgetter(item_choice)(inventory)
            if item == potion:
                global User_HP
                User_HP += 5
                lcd_print(User_HP)
                break
        else:
            lcd_print(textscroll("ERROR! ITEM CHOICE IS AN INVALID OPTION!"))

#Defend Function def defend(User):
    Enemy_damage = randint(1,3)
    lcd_print(textscroll(f"The user blocked {Enemy_damage} damage"))

#Text Scrolling Function def textscroll(text):
    from time import sleep

    i = 0
    j = 15
    while True:
        lcd_print(text[i:j])
        i += 1
        j += 1
        sleep(0.2)
        lcd_clear()
        if j >= len(text) + 15:
            break

1 Ответ

1 голос
/ 09 апреля 2020

У вас ошибка, потому что вы не присвоили ей значение (даже если вы сказали):

исключение NameError : возникает при локальном или глобальном имени не найден. Это относится только к неквалифицированным именам. Связанное значение представляет собой сообщение об ошибке, которое включает имя, которое не может быть найдено.

Источник: https://docs.python.org/3/library/exceptions.html#bltin-исключения


Проблема в вашем коде вы пытаетесь получить доступ к переменным из одного файла, не импортируя их . Глобальные переменные существуют только внутри файла, в котором они определены. Просто импортируйте их как функции:

import Enemy_HP
...