変数 'health'を別のモジュールからインポートしたにもかかわらず、以下の関数はタイトルに示されているエラーを提供します。 「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'に値が0より大きいかどうかをチェックする前に値を割り当てる必要があります。あなたはそれをやっていません。エラーメッセージは私には明らかです... –
他のモジュールが所有している 'health'の値が必要な場合は、その値にアクセスできる関数呼び出しからパラメータとして渡すか、このモジュールに、その値を呼び出す方法を提供する必要があります。たとえば、 'health'の状態を維持するオブジェクトがあるとします。この場合、直接アクセスすることも、アクセサー関数を提供することもできます。 –
この場合、 'health'は文字のようなものの本質的な特徴であるため、' health'を報告するのではなく、他のオブジェクトがヒットするための方法を提供するCharacterオブジェクトを提供することをお勧めします。キャラクターはそれ自身にダメージを与える責任があります。例えば、ヘルスが0以下の場合は死ぬでしょう。 –