这是我得到的错误:
Traceback (most recent call last):
File "C:\Users\Mendel Hornbacher\My programs\Spaceblaster\SpaceBlaster0.0.2b.py", line 95, in <module>
animate()
File "C:\Users\Mendel Hornbacher\My programs\Spaceblaster\SpaceBlaster0.0.2b.py", line 53, in animate
ship.hit(astroid_list)
File "C:\Users\Mendel Hornbacher\My programs\Spaceblaster\SpaceBlaster0.0.2b.py", line 34, in hit
if pygame.sprite.spritecollide(self, item, False):
File "C:\Python33\lib\site-packages\pygame\sprite.py", line 1515, in spritecollide
return [s for s in group if spritecollide(s.rect)]
TypeError: 'Astroid' object is not iterable
这些是涉及的课程:
动画:
def animate():
ship.hit(astroid_list)
ship.move()
screen.fill([0,0,0])
astroid_list.draw(screen)
screen.blit(ship.image, ship.rect)
pygame.display.flip()
self.hit(在&#39; Ship&#39;班级)
def hit(self, group):
for item in group:
group.remove(item)
if pygame.sprite.spritecollide(self, item, False):
self.die()
group.add(item)
astroid_list
astroid_list = pygame.sprite.Group()
如果这意味着我正在运行Windows 8专业版。 如果上述代码不够,我会将整个代码发布在评论中。
答案 0 :(得分:2)
当你想要获得spritecollide
个精灵时,你将一个精灵传递给list
。这导致抛出异常,因为Astroid
不是可迭代的类。
def hit(self, group):
if pygame.sprite.spritecollide(self, group, False):
self.die()
文档中的一个小小提示是pygame.sprite.spritecollideany
比常规spritecollide
略快一些,可能是一个更好的选择,因为你不关心你碰到它的是什么,所以你不要需要返回你碰到的东西。
答案 1 :(得分:0)
spritecollide
function期望您传递Group
,而非个人精灵。
只需一次性测试整个小组:
def hit(self, group):
if pygame.sprite.spritecollide(self, group, False):
self.die()
现在,您还可以避免在循环播放列表时删除和添加项目。
如果要删除组中的精灵self
,请在致电spritecollide()
后执行此操作:
def hit(self, group):
collided = pygame.sprite.spritecollide(self, group, False)
for item in collided:
group.remove(item)
if collided:
self.die()
您可以将dokill
标记设置为True,而不是手动删除每个项目,它们将从您的组中删除:
def hit(self, group):
if pygame.sprite.spritecollide(self, group, True):
self.die()
如果你不需要知道哪些项目发生了冲突而又不想从群组中删除项目,请改用spritecollideany()
;它只返回True或False并且更快:
def hit(self, group):
if pygame.sprite.spritecollideany(self, group):
self.die()