2013-09-30 57 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

相关问题