儘管從其他模塊導入了變量「health」,但下面的函數提供了標題中顯示的錯誤。 「健康」也是全球化的,我已經刪除了全球化和變量的輸入,我仍然收到同樣的錯誤。Python - UnboundLocalError:分配之前引用的局部變量'health'
下面是導致問題的功能。
def combat():
enemy_health = (random.choice(random_enemy_Health))
enemy_attack = (random.choice(random_enemy_Attack))
print("\nYou are fighting a" ,random.choice(enemies), "with an attack amount of" ,enemy_attack, "and a health amount of" ,enemy_health,".")
while health > 0 and enemy_health > 0:
if turn == 1:
while loop == False:
response=input()
try:
move = response("Do you want to attack or flee? Type '1' to attack and '2' to flee.")
move = int(move)
if move == 1:
enemy_health = enemy_health - attack
print("You attacked!")
loop = True
elif move == 2:
hub_travel()
print("You fled the battle, come back once you are stronger!")
loop = True
else:
print("Invalid number, try again")
continue
except:
print("Invalid number, try again")
continue
turn = 2
if turn == 2:
AImove = randint(1,2)
if AImove == 1:
print ("Enemy attacked!")
health = health - enemy_attack
turn = 1
continue
print ("game over!")
if enemy_health == 0:
print("The enemy has been defeated!")
gold += random.choice(gold_dropped)
錯誤發生在這條線具體爲:
while health > 0 and enemy_health > 0:
在檢查它是否大於零之前,您必須爲'health'分配一個值。你沒有這樣做。錯誤信息對我來說似乎很清楚...... –
如果您需要由另一個模塊擁有的'health'的值,則需要將其作爲參數從具有該值訪問權限的函數調用中傳入,或者您需要爲該模塊提供調用該值的方法。例如,您可能有一個維護「健康」狀態的對象,在這種情況下,您可以直接訪問它或提供訪問者函數。 –
在這種情況下,「健康」是某個角色的內在特徵,您最好提供一個Character對象,而不是報告其「健康狀況」,以便爲另一個對象提供某種方式來實現它。然後角色將負責將損害應用於自身,例如,如果健康<0或類似的東西會死亡 –