在我的策略游戏 Table Wars 的一场长时间比赛中,我遇到了这个错误。每当战场上有许多单位时,它似乎就会发生。这是回溯:
Traceback (most recent call last):
File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 727, in <module>
main()
File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 131, 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 372, in update
self.attack()
File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 393, in attack
self.target.health -= self.attack_damage
AttributeError: 'NoneType' object has no attribute 'health'
异常似乎出现在目标和攻击代码中,所以我将它们发布在这里:
def move_toward(self, target):
if self.target is None:
self.rect.move_ip(1, 0)
def update(self):
self.find_target()
self.move_toward(self.target)
self.attack()
if self.health <= 0:
self.kill()
def find_target(self):
if self.target is not None: return
for enemy in BluTeam.sprites():
if enemy.rect.centerx - self.rect.centerx <= self.range and enemy.rect.centery - self.rect.centery <= self.range:
self.target = enemy
return
self.target = None
def attack(self):
global REDGOLD
global BLUECOMMAND
if self.target is None: return
if self.target.health <= 0:
REDGOLD += self.target.reward
BLUECOMMAND += self.target.cmdback
self.target = None
if not self.cooldown_ready(): return
self.target.health -= self.attack_damage
def cooldown_ready(self):
now = pygame.time.get_ticks()
if now - self.attack_last >= self.attack_cooldown:
self.attack_last = now
return True
return False
我该如何解决?