在Python中编写游戏循环的正确方法是什么?

jas*_*str 4 python game-engine game-loop

我正在尝试编写一个python游戏循环,希望考虑到FPS.调用循环的正确方法是什么?我考虑过的一些可能性如下.我试图不使用像pygame这样的库.

1.

while True:
    mainLoop()
Run Code Online (Sandbox Code Playgroud)

2.

def mainLoop():
    # run some game code
    time.sleep(Interval)
    mainLoop()
Run Code Online (Sandbox Code Playgroud)

3.

 def mainLoop():
    # run some game code
    threading.timer(Interval, mainLoop).start()
Run Code Online (Sandbox Code Playgroud)

4.使用sched.scheduler?

Ale*_*lex 12

如果我理解正确,您希望将游戏逻辑建立在时间增量上.

尝试在每个帧之间获得时间增量,然后让对象相对于该时间增量移动.

import time

while True:
    # dt is the time delta in seconds (float).
    currentTime = time.time()
    dt = currentTime - lastFrameTime
    lastFrameTime = currentTime

    game_logic(dt)


def game_logic(dt):
    # Where speed might be a vector. E.g speed.x = 1 means
    # you will move by 1 unit per second on x's direction.
    plane.position += speed * dt;
Run Code Online (Sandbox Code Playgroud)

如果您还希望每秒限制帧数,那么在每次更新后,一种简单的方法就是在适当的时间内休眠.

FPS = 60

while True:
    sleepTime = 1./FPS - (currentTime - lastFrameTime)
    if sleepTime > 0:
        time.sleep(sleepTime)
Run Code Online (Sandbox Code Playgroud)

请注意,只有当您的硬件对游戏来说足够快时才会有效.有关游戏循环的更多信息,请检查此项.

PS)抱歉Javaish变量名称......刚从Java编码中休息了一下.