2013-09-30 51 views
0

正如您可能已經通過下面的明顯標誌所意識到的那樣,我正在嘗試創建一個遊戲,一個模擬戰鬥類型。這是一個非常基礎的課程任務,我們必須製作一個簡單的遊戲(我可能會讓它變得更加複雜,但我希望玩得開心。目前,我們有主循環,如果用戶的健康狀況大於零,這是在開始時(100),他進行第一次戰鬥,如果他通過所有戰鬥仍然超過100,他贏了,如果它低於100,他輸了我的問題是,在測試時,如果健康的確會走低,用戶的健康做了,因爲下面的錯誤不是我在Python 2.7版,如果這是一個需要了解的信息UnboundLocalError:分配前引用的局部變量「user_health」

Traceback (most recent call last): 
File "a3.py", line 109, in <module> 
fighting_arena() 
File "a3.py", line 63, in fighting_arena 
menu_loop() 
File "a3.py", line 37, in menu_loop 
main_loop() 
File "a3.py", line 69, in main_loop 
easy_fight() 
File "a3.py", line 96, in easy_fight 
print "You have %s health and Hagen has %s health left." % (user_health, easy_opponent_health) 
UnboundLocalError: local variable 'user_health' referenced before assignment 

- 。

def main_loop(): 
global user_health 
user_health = 100 
while user_health > 0: 
    easy_fight() 
    end_game_victory() 
else: 
    end_game_defeat() 

def easy_fight(): 
easy_opponent_health = 50 
easy_opponent_skills = ['1', '2', '3', '4'] 
print '"Your first opponent is Hagen, a germanic gladiator. He bares no armor, but he has a shield and uses a long sword. Beware of his vicious strength!"' 
time.sleep(2) 
print 'You enter the arena surrounded by thousands of Romans demanding blood with Hagen across the field. The fight begins!' 
while easy_opponent_health > 0: 
    a = raw_input() 
    b = random.choice(easy_opponent_skills) 
    if a == "1" and b == "1": 
     print "You both slashed each other!" 
     user_health -= 5 
     easy_opponent_health -= 5 
     print "You have %s health and Hagen has %s health left." % (user_health, easy_opponent_health) 
    elif a == "1" and b == "2": 
     print "You slashed Hagen while he managed to get a non-lethal stab!" 
     user_health -= 2.5 
     easy_opponent_health -= 5 
     print "You have %s health and Hagen has %s health left." % (user_health, easy_opponent_health) 
    elif a == "1" and b == "3": 
     print "Your slash only scratched Hagen as he dodged it!" 
     easy_opponent_health -= 2.5 
     print "You have %s health and Hagen has %s health left." % (user_health, easy_opponent_health) 
    elif a == "1" and b == "4": 
     print "Your slash was blocked by Hagen!" 
+1

請修復您的縮進。 – sashkello

回答

2

user_healthmain_loop函數中定義,所以只能通過該函數進行訪問,除非將其全局化。你在main_loop()

範圍分配user_health = 100

def main_loop(): 
    global user_health 
    user_heal = 100 
    ... 
+0

所以這樣? global user_health = 100 – GOAT

+0

@GOAT檢查我編輯的答案 – TerryA

+0

它仍然認爲它是一個局部變量。我是否應該縮進「user_health = 100」,並且應該在main_loop內,還是應該從main_loop中取出「global user_health」? – GOAT

2

但你在easy_fight()使用它,這就是爲什麼你的錯誤,因爲它只有在main_loop()一個變量:

global user_health定義user_health = 100

解決方法是使用global關鍵字全局化變量,或者創建一個類並使其他們的類變量

更多有關variable scope

+0

我試圖全球化,但它沒有工作,代碼在原始問題中更新。有小費嗎?如果它不可能,我會如何將它放入課堂?對不起,我仍然不喜歡。 – GOAT

相關問題