gpt4 book ai didi

python - 全局变量未绑定(bind)局部错误

转载 作者:太空狗 更新时间:2023-10-29 21:24:53 25 4
gpt4 key购买 nike

<分区>

我想弄清楚为什么我的 pygame 应用程序 Table Wars 会出现 UnboundLocalError。以下是所发生情况的摘要:

变量 REDGOLDREDCOMMANDBLUEGOLDBLUECOMMAND 被初始化为全局变量:

#Red Stat Section
REDGOLD = 50
REDCOMMAND = 100
#Blue Stat Section
BLUEGOLD = 50
BLUECOMMAND = 100

def main():

[...]

global REDGOLD
global REDCOMMAND
global BLUEGOLD
global BLUECOMMAND

这在主循环中生成单位时起作用,减去生成单位的资金。

现在,我正在尝试建立一个系统,以便当一个单位死亡时, killer 会退还受害者的 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 block 改变?如果有帮助,我正在使用 Pygame 2.7.x,所以 nonlocal 将不起作用:/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com