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

1

5

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?

Mimas answered 30/4, 2013 at 13:31 Comment(4)
The second and the third options start the same method from itself, so there will be something growing over time…Smew
"I do not want to use a framework like pygame" -- Then what do you want to use? Tkinter? I think you need to tell us what you plan on doing before we can give you any recommendations.Vitrine
Also, 1 should be written as while True: :)Vitrine
Not sure what I'll use for the GUI yet. I essentially have hundreds of planes flying around and need to update their positions.Mimas
V
18

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.

Vanbuskirk answered 30/4, 2013 at 14:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.