1

我刚刚开始使用 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 中实现“多帧”的首选方式是什么?

4

1 回答 1

1

For the lower part, I suggest you just say

frame.logic()
frame.draw()

and make sure your frame object provides the logic and draw methods.

As for the upper part, where you determine what your current frame actually is, it's a little trickier. I would probably set a boolean flag is_finished on each frame, allowing your loop to determine whether it can proceed to the subsequent frame. So I'd replace the code

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

by sth like

if frame.is_finished:
    frame = successor(frame)

Then you'd have to find a sensible way to determine each frame's successor. This should happen outside of your frames' implementation, so that the frame does not need to know its successor.

As for the mouse/key events: I'd pass them into the current frame objects to handle them. The object will possibly set its is_finished flag to True after processing them.

于 2013-11-04T09:16:30.060 回答