我有一个气球需要每 3 秒爆炸一次的游戏,但爆炸需要延迟大约 1 秒(现在,它几乎是立即的)。我每 3 秒就有一次气球下降,但我在延迟部分遇到了麻烦。如果我使用睡眠或等待,我正在进行的所有其他动画都会停止,这不是我想要的。有没有人有任何提示?
这是一个完整的例子。我强烈推荐使用面向对象编程、pygame sprites 和 sprite group。这些精灵有一个timer
属性,它会随着dt
每帧的增量时间而减少。当气球的时间到了时,它会从包含的精灵组中移除,balloon.kill()
并添加一个爆炸实例。爆炸也有一个计时器并self.kill()
在计时器低于 时自行移除0
。(按鼠标按钮可添加更多气球。)
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
# Images. Balloon = blue, explosion = orange.
BALLOON_IMAGE = pg.Surface((50, 50), pg.SRCALPHA)
pg.draw.circle(BALLOON_IMAGE, pg.Color('steelblue2'), (25, 25), 25)
EXPLOSION_IMAGE = pg.Surface((80, 80), pg.SRCALPHA)
pg.draw.circle(EXPLOSION_IMAGE, pg.Color('sienna1'), (40, 40), 40)
class Balloon(pg.sprite.Sprite):
def __init__(self, pos):
super().__init__()
self.image = BALLOON_IMAGE
self.rect = self.image.get_rect(center=pos)
self.timer = 3
def update(self, dt):
self.timer -= dt
class Explosion(pg.sprite.Sprite):
def __init__(self, pos):
super().__init__()
self.image = EXPLOSION_IMAGE
self.rect = self.image.get_rect(center=pos)
self.timer = 1
def update(self, dt):
self.timer -= dt
if self.timer <= 0:
self.kill()
balloons = pg.sprite.Group(Balloon((300, 300)))
all_sprites = pg.sprite.Group(balloons)
done = False
while not done:
dt = clock.tick(30) / 1000
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.MOUSEBUTTONDOWN:
balloon = Balloon(event.pos)
balloons.add(balloon)
all_sprites.add(balloon)
all_sprites.update(dt)
for balloon in balloons:
if balloon.timer <= 0:
balloon.kill()
all_sprites.add(Explosion(balloon.rect.center))
screen.fill((30, 30, 30))
all_sprites.draw(screen)
pg.display.flip()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句