在Python Crash Course中的太空入侵者项目中,我们需要在子弹离开屏幕边界后将其从组中移除。这是通过实现的
for bullet in self.bullets.copy():
if bullet.rect.bottom <= 0:
self.bullets.remove(bullet)
在保存并按原样运行程序后,游戏似乎已经慢了很多,以至于无法播放。我改变了子弹的速度,但比赛变得断断续续。删除功能所在的游戏结构有点像这样:
while True: # main game loop
--snip--
self.game_updates() # other game functions
self._update_bullets() # updating the bullets
--snip--
def _update_bullets():
self.bullets.update() # updates the rect.y of the bullets. self.bullets is the Group.
for bullet in self.bullets.copy():
if bullet.rect.bottom <= 0:
self.bullets.remove(bullet)
我确信不是if语句或循环结构减缓了它的速度,而是remove((函数。我试着用打印语句替换remove,它没有任何延迟。
如何解决这个问题?
(如果你想查看整个项目,这里有链接。(
self.bullets
是一个pygame.sprite.Group()
对象。如果要删除pygame.sprites.Sprite
对象,必须调用kill
:
从所有群组中移除精灵
for bullet in self.bullets:
if bullet.rect.bottom <= 0:
bullet.kill()
使用此解决方案,您不需要copy
和pygame.sprite.Group
。