Python 对象是不可编辑的
以下是我得到的错误:Python 对象是不可编辑的,python,python-3.x,python-3.3,Python,Python 3.x,Python 3.3,以下是我得到的错误: 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.
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
astroid_list = pygame.sprite.Group()
如果上面的代码不够,我将在注释中发布整个代码。您正在将单个精灵传递给
spritecollide
,而它希望获得精灵的列表。这导致抛出异常,因为您的Astroid
不是一个iterable类
def hit(self, group):
if pygame.sprite.spritecollide(self, group, False):
self.die()
文档中的一个很好的小提示是pygame.sprite.spritecollideany
比常规的spritecollide
稍微快一点,并且可能是一个更好的选择,因为您不关心与它发生冲突的内容,所以您不需要返回与它发生冲突的内容。希望您通过,不是单个的精灵
只需一次完成整个团队的测试:
def hit(self, group):
if pygame.sprite.spritecollide(self, group, False):
self.die()
现在,您还可以避免在列表上循环时删除和添加项目
如果要从组中删除与碰撞的精灵self
,请在调用spritecollide()
后执行此操作:
但是,您可以将dokill
标志设置为True,而不是手动删除每个项目,它们将为您从组中删除:
def hit(self, group):
if pygame.sprite.spritecollide(self, group, True):
self.die()
如果您不需要知道哪些项目发生冲突,也不想从组中删除项目,请改用;它只返回True或False,速度更快:
def hit(self, group):
if pygame.sprite.spritecollideany(self, group):
self.die()
顺便说一句,您将无法在注释中发布整个代码。但是您可以在问题中编辑更多信息(请参见编辑链接),您不应该在迭代对象的同时尝试删除它们。
def hit(self, group):
collided = pygame.sprite.spritecollide(self, group, False)
for item in collided:
group.remove(item)
if collided:
self.die()
def hit(self, group):
if pygame.sprite.spritecollide(self, group, True):
self.die()
def hit(self, group):
if pygame.sprite.spritecollideany(self, group):
self.die()