Error local no consolidado con variable global
Estoy tratando de averiguar por qué obtengo UnboundLocalError en mi aplicación de pygame, Table Wars. Aquí hay un resumen de lo que sucede:
Las variables,REDGOLD
, REDCOMMAND
, BLUEGOLD
yBLUECOMMAND
, se inicializan como variables globales:
#Red Stat Section
REDGOLD = 50
REDCOMMAND = 100
#Blue Stat Section
BLUEGOLD = 50
BLUECOMMAND = 100
def main():
[...]
global REDGOLD
global REDCOMMAND
global BLUEGOLD
global BLUECOMMAND
Esto funciona cuando se generan unidades dentro del bucle principal, restando fondos a las unidades de generación.
En este momento, estoy tratando de configurar un sistema para que cuando una unidad muere, el asesino devuelva el dinero de la víctima.COMMAND
y ganaGOLD
basado en lo que mató:
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
Esto funciona hasta que la unidad muere. Entonces esto sucede:
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
¿Cómo consigo que las variables globales mencionadas anteriormente cambien con laattack
¿bloquear? Si ayuda, estoy usando Pygame 2.7.x, entoncesnonlocal
no funcionará: /