尝试做动画,但程序会在它之前关闭

时间:2015-11-13 18:09:25

标签: python pygame

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

    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

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

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

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

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