简体   繁体   English

未绑定错误,分配前已引用局部变量

[英]Unbound error, local variable referenced before assignment

I'm making a small text game for fun. 我正在做一个小型的文字游戏,很有趣。 I want to use a function which is located in a function file that I made called functionala. 我想使用位于我创建的称为Functionala的功能文件中的功能。

The function in question, attack() , does not work and the program crashes with the error: 有问题的函数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

The new and improved version of the functionala file is what seems to be causing the problem: 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()

This seems a cleaner way of doing it, all in a single file. 这似乎是一种更干净的方法,全部都在一个文件中。 you may want to look at using classes. 您可能想看看使用类。

From console, call game() to start the game, that's it. 从控制台中,调用game()即可开始游戏。 The game will end when either monster or you have health <= 0. 当怪物或您的生命值小于等于0时,游戏将结束。

Code: 码:

from random import randrange

def game():
    stamina = 20
    health = 40
    monsterhealth = 30
    monster = 'orc'
    attacks = {'light':(-2,0),'medium':(-4,-2),'heavy':(-7,-4)}
    while True:
        a = input('you can execute 3 types of attacks, light, medium or heavy... pick one.')
        a = a.lower().strip()
        if a in attacks:
            stamina, health, monsterhealth = attack(stamina, health, monsterhealth, monster, attacks[a])
            if stamina <= 0:
                print 'you have died...'
                break
            elif monsterhealth <= 0:
                print 'the {} has died...'.format(monster)
                break
        else:
            break

def attack(stamina, health, monsterhealth, monster, att):
    monsterhealth += att[0]
    stamina += att[1]
    stamina = min(20, stamina)
    print('the {} has {} health remaining'.format(monster,monsterhealth))
    print('you have {} stamina remaining'.format(stamina))
    ma = randrange(4,6)
    health -= ma
    print('the {} attacks you for {}'.format(monster,ma))
    print('you have {} health left'.format(health))
    return stamina, health, monsterhealth

NB: Even doing this in a single file, you need to scope the variables to the "main" procedure ( game ), and pass them to the attack function. 注意:即使在单个文件中执行此操作,也需要将变量的作用域限定在“主要”过程( game )中,然后将其传递给attack函数。 Otherwise, referring to these names will raise the same error, and you can reproduce this like so: 否则,引用这些名称将引发相同的错误,您可以像这样重现该错误:

m = 1
def foo():
   m += 1  '## m doesn't exist within scope of foo, so it will raise the same error

HOWEVER, and this may be confusing, the following will not raise an error: 但是,这可能会造成混淆,以下内容不会引发错误:

m = 1
def foo():
   print m

Nor will this: 这也不会:

m = 1
def foo():
   a = m
   print a

But both of those seem kind of hack-y and it's usually better to pass values from the main procedure to called functions/methods/etc and return appropriate values to the caller. 但是,这两种方法似乎都是很不礼貌的,通常最好将值从主过程传递给被调用的函数/方法/ etc,然后将适当的值返回给调用者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM