python - 尝试制作动画,但程序会在此之前关闭

标签 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)开始之前运行。有没有更好的方式来完整地展示这个动画?

最佳答案

这听起来像是使用回调函数的情况。 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

关于python - 尝试制作动画,但程序会在此之前关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33699204/

相关文章:

python - Django 休息总是创建新实例

python - 如何根据每个组的大小设置滚动窗口大小?

python - 蛇游戏,但问题是,如果我向左移动蛇,然后向右移动蛇,蛇本身会崩溃或相反,上下相同

Python:创建带有可移动图钉的 map

python - 在不安装的情况下使用 Pygame

python - 使用变量而不是文字时出现断言错误

python - fuse -Python : Unable to run example

python - 比较表单字段值和查询集值的值

python - 将大空格键与 Raspberry Pi 连接

python-pygame 矩形不会绘制/渲染