Pygame - 在一段时间后删除/杀死 Sprite,无需轮询

Pygame - Remove / Kill Sprite after time period, without polling

每当我拍摄精灵时,我都希望能够将其从屏幕上移除,但只能在半秒后(或其他任意时间段)。但我不想轮询睡眠以等待该时间段结束。

这是我到目前为止的进展:

# detect collision here - all good
collisions = pygame.sprite.groupcollide(bullets, badGuys, True, False)
for baddies in collisions.values():
    for bad in baddies:
        # do stuff
        baddiesToRemove.appendleft(bad)
        # since a collision occured set timer for that specific bad guy:
        startTime = pygame.time.get_ticks()

# now after 500 milliseconds have passed, sth like that:
milis = pygame.time.get_ticks() - startTime # result in milliseconds
if (milis > 500):
    badGuyToRemove = baddiesToRemove.pop()
    badGuyToRemove.kill() # i want to delete the sprite

我希望上面的代码是可以理解的。简而言之,这是行不通的,除非我在中间插入一个 sleep() 等待一段时间,然后删除精灵。当然这不是一个选项,因为整个程序会在那个时间段内冻结。我想过也许创建一个线程来处理这个计时器? pygame / python 有更好的选择吗?有什么建议吗?提前致谢。

像动画一样做!

我假设您有某种已用时间 and/or 已用帧数计数器。我现在不在 IDE 并且不相信我的即时 pygame,但在您的更新函数中包含如下内容:

def update(...):
  ...
  if (not alive) and wait_frames:
    wait_frames -= 1
  if (not alive) and (not wait_frames):
    # remove
  ...

除非您的更新实现方式与我一直使用它的方式有很大不同,否则这应该可以解决问题![​​=11=]

每个敌人精灵都需要一个自己的计时器。如果一颗子弹击中了其中一​​个,则启动计时器,如果所需时间已经过去,请检查更新方法,然后调用 self.kill()。 (本例按任意键启动敌人的计时器。)

import sys
import pygame as pg


class Enemy(pg.sprite.Sprite):

    def __init__(self, pos, *groups):
        super().__init__(*groups)
        self.image = pg.Surface((50, 30))
        self.image.fill(pg.Color('sienna1'))
        self.rect = self.image.get_rect(center=pos)
        self.time = None

    def update(self):
        if self.time is not None:  # If the timer has been started...
            # and 500 ms have elapsed, kill the sprite.
            if pg.time.get_ticks() - self.time >= 500:
                self.kill()


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group()
    enemy = Enemy((320, 240), all_sprites)

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.KEYDOWN:
                # Start the timer by setting it to the current time.
                enemy.time = pg.time.get_ticks()

        all_sprites.update()
        screen.fill((30, 30, 30))
        all_sprites.draw(screen)

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
    sys.exit()