我想寫一個簡單的程序,定義兩個虛構的戰士只有一個名稱和數量的健康。簡單的1對1撲滅模擬
現在這就是我寫:
import random
def main():
pass
if __name__ == '__main__':
main()
hpRed = 20
hpBlu = 20
def attack():
damage = random.randrange(1,3)
return hpRed - damage
return hpBlue - damage
def fighterRed(name, hpRed):
print(str(name) + " has " + str(hpRed) + " health left.")
def fighterBlue(name, hpBlu):
print(str(name) + " has " + str(hpBlu) + " health left.")
def battle():
fighterRed("Branden",hpRed)
fighterBlue("Alex",hpBlu)
while ((hpRed > 0) and (hpBlu > 0) is True):
attack()
else:
print("The battle is over!")
if (hpRed > 0):
return "Red Player is victorious!"
else:
return "Blue Player is victorious!"
battle()
到目前爲止,我不斷收到錯誤消息「分配之前HPRED引用」。我可以更改哪些內容以正確傳遞hpRed和hpBlu的值?
雖然您發佈的代碼有許多問題,但它不會導致您提到的UnboundLocal異常。下一次,發佈您的_actual_代碼和錯誤消息的完整回溯。 – l4mpi