在Pygame中添加额外的“帧”

时间:2013-11-04 08:06:47

标签: python pygame

我刚刚开始使用Pygame,到目前为止我的所有程序都像这个伪代码一样运行:

initialize game
while true:
    for each event:
        if event is close button:
            close()
        elif event is mouse button down:
            event_handler()

    logic()
    draw()
    update_display()

这适用于一个“框架”。但是,如果我想要一个标题画面(例如,点击开始),主游戏(具有正常的事件处理),以及屏幕上的游戏(按键开始),该怎么办?我决定像这样实现它:

initialize game
frame = 0
while true:
    for each event:
        if event is close button:
            close()

        if frame == 0:
            if event is mouse button down:
                frame = 1

        elif frame == 1:
            if event is mouse button down:
                event_handler()

        elif frame == 2:
            if event is key button down:
                frame = 0

    if frame == 0:
        frame_zero_logic()
        frame_zero_draw()
    elif frame == 1:
        frame_one_logic()
        frame_one_draw()
    elif frame == 2:
        frame_two_logic()
        frame_two_draw()

    update_display()

但是,我觉得这不是最好的实施方式。在Pygame中实现“多帧”的首选方法是什么?

1 个答案:

答案 0 :(得分:1)

对于下半部分,我建议你说

frame.logic()
frame.draw()

并确保您的框架对象提供logicdraw方法。

至于上半部分,您确定当前frame实际上是什么,这有点棘手。我可能会在每个帧上设置一个布尔标志is_finished,允许您的循环确定它是否可以继续到后续帧。所以我要替换代码

if frame == 0:
    if event is mouse button down:
        frame = 1
    elif frame == 1:
        if event is mouse button down:
            event_handler()
    elif frame == 2:
        if event is key button down:
            frame = 0

喜欢

if frame.is_finished:
    frame = successor(frame)

然后你必须找到一种合理的方法来确定每个帧的后继者。这应该在框架的实现之外发生,因此框架不需要知道它的后继者。

关于鼠标/键事件:我将它们传递给当前帧对象来处理它们。在处理完对象后,该对象可能会将is_finished标志设置为True