我试图弄清楚为什么在我的游戏应用程序“桌战”中 会有一个无线本地错误。这里是所发生事情的概要:
变量 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:UsersOventoasterDesktopGamesTable WarsTable Wars.py", line 606, in <module>
main()
File "C:UsersOventoasterDesktopGamesTable WarsTable Wars.py", line 123, in main
RedTeam.update()
File "C:Python27libsite-packagespygamesprite.py", line 399, in update
for s in self.sprites(): s.update(*args)
File "C:UsersOventoasterDesktopGamesTable WarsTable Wars.py", line 304, in update
self.attack()
File "C:UsersOventoasterDesktopGamesTable WarsTable Wars.py", line 320, in attack
REDGOLD += self.target.reward
UnboundLocalError: local variable REDGOLD referenced before assignment
如何用 < code> attack code > 块改变上述全球变量? 如果有用, 我使用 Pygame 2.7. x, 所以 < code > nonlocal code > 将无法工作 : /