0

正如您可能已经通过下面的明显迹象意识到的那样,我正在尝试创建一个游戏,一种战斗模拟。一个非常基本的课堂作业,我们必须制作一个简单的游戏(我可能让它变得比它必须的更复杂,但我想玩得开心。目前,我们有一个主循环,如果用户的生命值大于零,在开始时(100)他继续进行第一场战斗,如果他通过所有战斗而仍然大于 100,他赢了。如果低于 100,他输了.我的问题是,当测试健康是否真的会变低时,用户的健康没有因为以下错误。如果需要知道信息,我在python 2.7上。

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!"
4

2 回答 2

2

user_health是在main_loop函数中定义的,因此只能从该函数访问它,除非您对其进行全球化。

放在global user_health定义之前user_health = 100

def main_loop():
    global user_health
    user_heal = 100
    ...
于 2013-09-30T00:12:12.320 回答
2

您分配user_health = 100的范围内main_loop()

但是后来你使用了它,easy_fight()这就是你得到错误的原因,因为它只是一个变量main_loop()

解决此问题的一种方法是使用 global 关键字将变量全球化,或者创建一个类并使它们成为类变量

更多关于变量范围

于 2013-09-30T00:13:10.270 回答