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

时间:2013-04-30 13:31:53

标签: python game-engine game-loop

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

1

while True:
    mainLoop()

2

def mainLoop():
    # run some game code
    time.sleep(Interval)
    mainLoop()

3

 def mainLoop():
    # run some game code
    threading.timer(Interval, mainLoop).start()

4。 使用sched.scheduler?

1 个答案:

答案 0 :(得分: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;

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

FPS = 60

while True:
    sleepTime = 1./FPS - (currentTime - lastFrameTime)
    if sleepTime > 0:
        time.sleep(sleepTime)

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

PS)对于Javaish变量名称感到抱歉......刚从Java编码中休息了一段时间。