Ove*_*ter 7 python debugging pygame
我试图弄清楚为什么我的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
Run Code Online (Sandbox Code Playgroud)
这在主循环中产生单位时减少了产生单位的资金.
现在,我正在尝试建立一个系统,以便当一个单位死亡时,杀手会根据他杀死的内容退还受害者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
Run Code Online (Sandbox Code Playgroud)
这一直有效直到装置死亡.然后这发生了:
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
Run Code Online (Sandbox Code Playgroud)
如何通过attack块更改上面提到的全局变量?如果它有帮助,我使用Pygame 2.7.x,所以nonlocal不会工作:/
global使全局变量在当前代码块中可见.你只把global声明放入main,而不是放入attack.
附录
以下是不止一次使用全球需求的说明.试试这个:
RED=1
def main():
global RED
RED += 1
print RED
f()
def f():
#global RED
RED += 1
print RED
main()
Run Code Online (Sandbox Code Playgroud)
你会得到错误UnboundLocalError: local variable 'RED' referenced before assignment.
现在取消注释f中的全局语句,它将起作用.
该global声明在LEXICAL中有效,而不是DYNAMIC范围.