What's the proper way to write a game loop in Python?

jastr picture jastr · Apr 30, 2013 · Viewed 15.8k times · Source

I'm trying to write a python game loop that hopefully takes into account FPS. What is the correct way to call the loop? Some of the possibilities I've considered are below. I'm trying not to use a library like 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. Use sched.scheduler?

Answer

Alex picture Alex · Apr 30, 2013

If I understood correctly you want to base your game logic on a time delta.

Try getting a time delta between every frame and then have your objects move with respect to that time delta.

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;

If you also want to limit your frames per second, an easy way would be sleeping the appropriate amount of time after every update.

FPS = 60

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

Be aware thought that this will only work if your hardware is more than fast enough for your game. For more information about game loops check this.

PS) Sorry for the Javaish variable names... Just took a break from some Java coding.