Erro local não ligado com variável global
Eu estou tentando descobrir por que recebo um UnboundLocalError no meu aplicativo pygame, o Table Wars. Aqui está um resumo do que acontece:
As variáveisREDGOLD
, REDCOMMAND
, BLUEGOLD
eBLUECOMMAND
, são inicializados como variáveis globais:
#Red Stat Section
REDGOLD = 50
REDCOMMAND = 100
#Blue Stat Section
BLUEGOLD = 50
BLUECOMMAND = 100
def main():
[...]
global REDGOLD
global REDCOMMAND
global BLUEGOLD
global BLUECOMMAND
Isso funciona ao gerar unidades dentro do loop principal, subtraindo fundos para gerar unidades.
Neste momento, estou tentando montar um sistema para que quando uma unidade morra, o assassino restitua a vítimaCOMMAND
e ganhaGOLD
com base no que ele matou:
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
Isso funciona até a unidade morrer. Então isso acontece:
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
Como obtenho as variáveis globais mencionadas acima para mudar com oattack
quadra? Se isso ajudar, estou usando o Pygame 2.7.x, entãononlocal
não vai funcionar: /