尝试制作动画,但程序会先于它关闭

Trying to do animation but the program would close before it

我是初学者,想知道是否有任何方法可以在程序关闭之前完成当前动画。这是代码示例:

    if playerHealth <= 0: # If the player dies
        expl = Explosion(hit.rect.center, 'lg')
        all_sprites.add(expl) # Show animation of him blowing up
        running = False # End the game

基本上 运行ning = False 代码会在动画 (expl) 开始之前 运行。有没有更好的方式来完整展示这个动画?

可能您需要更多修改,但其中之一是:

if playerHealth <= 0 and not blowing_up_animation_started: # If the player dies
    expl = Explosion(hit.rect.center, 'lg')
    all_sprites.add(expl) # Show animation of him blowing up

    blowing_up_animation_started = True
    blowing_up_animation_finished = False

if blowing_up_animation_finished:
    running = False # End the game

这听起来像是使用回调函数的情况。 Pygame 的 animation class 具有 on_finished 属性,旨在分配给回调。一旦动画播放完毕并停止游戏,就会调用回调。这是一个爆炸示例 class.

class Explosion:

    def __init__(self, rect, size, cb_func):

         self.animate_explosion(cb_func)

    ...

    def animate_explosion(self, cb_func):
         # start animation here

         ...

         # when animation finishes
         self.on_finished = cb_func()

然后在您的游戏逻辑中,您有如下内容:

def callback():
     running = False

if playerHealth <= 0: # If the player dies
     expl = Explosion(hit.rect.center, 'lg', callback())
     all_sprites.add(expl) # Show animation of him blowing up