我试图弄清楚为什么在我的 pygame 应用程序 Table Wars 中出现 UnboundLocalError。以下是所发生情况的摘要:
变量 ,REDGOLD
和,REDCOMMAND
被初始化为全局变量:BLUEGOLD
BLUECOMMAND
#Red Stat Section
REDGOLD = 50
REDCOMMAND = 100
#Blue Stat Section
BLUEGOLD = 50
BLUECOMMAND = 100
def main():
[...]
global REDGOLD
global REDCOMMAND
global BLUEGOLD
global BLUECOMMAND
这在主循环中生成单位时有效,从生成单位中减去资金。
现在,我正在尝试建立一个系统,以便当一个单位死亡时,杀手退还受害者COMMAND
并GOLD
根据他杀死的东西获得收入:
class Red_Infantry(pygame.sprite.Sprite):
def __init__(self, screen):
[...]
self.reward = 15
self.cmdback = 5
[...]
def attack(self):
if self.target is None: return
if self.target.health <= 0:
REDGOLD += self.target.reward #These are the problem lines
BLUECOMMAND += self.target.cmdback #They will cause the UnboundLocalError
#when performed
self.target = None
if not self.cooldown_ready(): return
self.target.health -= self.attack_damage
print "Target's health: %d" % self.target.health
这一直有效,直到单位死亡。然后会发生这种情况:
Traceback (most recent call last):
File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 606, in <module>
main()
File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 123, in main
RedTeam.update()
File "C:\Python27\lib\site-packages\pygame\sprite.py", line 399, in update
for s in self.sprites(): s.update(*args)
File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 304, in update
self.attack()
File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 320, in attack
REDGOLD += self.target.reward
UnboundLocalError: local variable 'REDGOLD' referenced before assignment
如何让上面提到的全局变量随attack
块而变化?如果有帮助,我正在使用 Pygame 2.7.x,所以nonlocal
不会工作:/