Pygame在时间段后移除/杀死精灵,无需轮询

2024-05-17 19:18:35 发布

您现在位置:Python中文网/ 问答频道 /正文

每当我拍摄精灵的时候,我都希望能够把它从屏幕上移除,但是只有在半秒之后(或者其他一些任意的时间段)。但我不想让睡眠等待这段时间的结束。在

到目前为止,我的目标是:

# 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有更好的选择吗?有什么建议吗?提前谢谢。在


Tags: inforgetthattimepygame精灵bad
2条回答

像动画一样做!在

我假设你有某种时间流逝和/或帧流逝计数器。我现在不在IDE中,不信任我的即时pygame,但在您的更新函数中包含以下内容:

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

除非您的更新实现与我一直使用它的方式不同,否则这应该能解决问题!在

每个敌人的精灵都需要自己的计时器。如果子弹击中其中一个,启动计时器,如果所需的时间已过,请检查update方法,然后调用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()

相关问题 更多 >