0
我正在做一個小的文本遊戲的樂趣之前引用局部變量。我想使用位於我稱之爲functionala的函數文件中的函數。未綁定錯誤,分配
問題,attack()
功能,不工作,程序與錯誤崩潰:
Traceback (most recent call last):
File "C:\Users\seanm\Desktop\Programming\The mists of Alandria\Mists_of_alandria.py", line 22, in <module>
functionala2.attack()
File "C:\Users\seanm\Desktop\Programming\The mists of Alandria\functionala2.py", line 27, in attack
variablestamina += 2
UnboundLocalError: local variable 'variablestamina' referenced before assignment
的functionala文件的新的和改進的版本是什麼似乎會引起問題:
variablestamina = 20
variablehealth = 40
variablemonsterhealth = 30
variableattacktype1 = ("Lightattack")
variableattacktype2 = ("Mediumattack")
variableattacktype3 = ("Heavyattack")
def attack():
variableattackquery = input("You can execute three types of attacks. Lightattack does 2 damage and takes no stamina. Mediumattack does 4 damage and takes 2 stamina. Heavyattack does 7 damage and takes 5 stamina. You can only do one per turn: ")
if variableattackquery == variableattacktype1:
variablemonsterhealth -= 2
variablestamina -= 2
if variableattackquery == variableattacktype2:
variablemonsterhealth -= 4
variablestamina -= 4
if variableattackquery == variableattacktype3:
variablemonsterhealth -= 7
variablestamina -= 7
variablestamina += 2
variablestamina = min(20, variablestamina)
print ("The "+monster+" has "+str(variablemonsterhealth)+" health left")
print ("You have "+str(variablestamina)+" stamina left")
monsterattack = random.randrange(4,6)
variablehealth -= monsterattack
print ("The "+monster+" attacks you for "+str(monsterattack))
print ("You have "+str(variablehealth)+" health left")
print()
是縮進如圖這個問題一樣在你的代碼?你的第一個片段對於第一行有過多的縮進,對於一個打印語句來說太少了。您的第二個片段對所有行都有多餘。縮進在Python中很重要! –
所以你有兩個文件,每個文件導入另一個文件?儘管這並不是Python嚴格禁止的,但它通常會導致混淆錯誤消息或令人驚訝的行爲,這似乎就是這種情況。嘗試重新設計您的代碼,避免循環導入。 – Kevin
@Rory Daulton不,我的縮進在這裏是錯誤的,它在文件中是不一樣的。很抱歉,不能找到一個方法來導入代碼以原始格式的 –