我有这个游戏,气球需要每3秒爆炸一次,但爆炸需要延迟大约1秒(现在,它几乎立即)。我每隔3秒就把气球放下,但是我在延迟部分遇到了麻烦。如果我使用睡眠或等待,我停止的所有其他动画都会停止,而这不是我想要的。有人有任何提示吗?
答案 0 :(得分:0)
这是一个完整的例子。我强烈建议使用面向对象的编程,pygame精灵和精灵组。这些精灵具有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()