The game loop

Every frame, a game reads input, updates the world and draws the result. Learn how to structure that loop, cap the frame rate and move things at the same speed on every computer.

Beginner4 min readUpdated
On this page

What you'll learn

  • The three phases of a frame and why their order matters
  • How clock.tick() controls the frame rate
  • Delta time: moving objects in pixels per second instead of pixels per frame
  • How to write a loop that also runs in a web browser

Prerequisites: Getting started.

The three phases of a frame#

A game is a loop that runs many times per second. Each pass, called a frame, does three things in order:

  1. Handle events: read what the player did since the last frame (keys, mouse, window close).
  2. Update: move objects, check collisions, change scores and timers.
  3. Draw: clear the screen, draw everything in its new position, then show it with pygame.display.flip().

Keeping these phases separate makes games easier to reason about. Update code never draws; drawing code never changes the game state. When something looks wrong you know where to look.

Python
while running:
    # 1. Events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 2. Update
    player.update()

    # 3. Draw
    screen.fill("black")
    player.draw(screen)
    pygame.display.flip()
    clock.tick(60)

Controlling the frame rate with clock.tick()#

clock = pygame.time.Clock() creates a clock. Calling clock.tick(60) once per frame does two things:

  • It waits if the frame finished early, so the loop runs at most 60 times per second.
  • It returns the number of milliseconds since the previous call.

Without a frame-rate cap your loop runs as fast as it can, using a full CPU core and draining laptop batteries. 60 FPS is a good default because most monitors refresh at 60 Hz or more. clock.get_fps() reports the average frame rate actually achieved.

Delta time: same speed on every computer#

Suppose you move a box with x += 5 each frame. At 60 FPS it moves 300 pixels per second, but on a slow machine running at 30 FPS it moves only 150. Game speed then depends on hardware, which is rarely what you want.

The fix is to measure speed in pixels per second and multiply by the time the last frame took, called delta time or dt:

game_loop_dt.pyDownload
"""Frame-rate independent movement: the same speed at 30, 60 or 144 FPS."""
import pygame

WIDTH, HEIGHT = 640, 360
SPEED = 200          # pixels per second, not per frame

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 28)

fps_options = [30, 60, 144]
fps_index = 1
x = 0.0

running = True
while running:
    dt = clock.tick(fps_options[fps_index]) / 1000   # seconds since last frame
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            fps_index = (fps_index + 1) % len(fps_options)   # cycle the cap

    x += SPEED * dt
    if x > WIDTH:
        x -= WIDTH + 40

    screen.fill((20, 26, 46))
    pygame.draw.rect(screen, (244, 197, 49), (round(x), 160, 40, 40))
    info = f"Cap {fps_options[fps_index]} FPS | actual {clock.get_fps():.0f} | Space changes the cap"
    screen.blit(font.render(info, True, (230, 236, 247)), (16, 16))
    pygame.display.flip()

pygame.quit()

Press Space while it runs to switch the cap between 30, 60 and 144 FPS. The box moves at the same speed each time, only more or less smoothly.

The delta time demo showing a yellow box and the current frame rate cap
game_loop_dt.py: the box speed stays at 200 pixels per second whatever the frame rate

Two details matter:

  • clock.tick(...) / 1000 converts milliseconds to seconds, so SPEED * dt is "pixels this frame".
  • The position is stored as a float (x = 0.0). pygame.Rect holds whole numbers only; if you add 0.4 pixels to a Rect every frame it rounds away and never moves. Keep a float and copy the rounded value into the Rect. pygame-ce also has pygame.FRect, which stores floats directly.
Clamp very large dt values

If the window is dragged or the computer stalls, one frame can take half a second, and a big dt makes objects jump through walls. Many games cap it: dt = min(clock.tick(60) / 1000, 0.05).

A loop that also runs in the browser#

In a web page, Python can't run an endless while loop because the browser only redraws when your code gives control back. The fix is small: put the loop in an async function and await asyncio.sleep(0) once per frame. The program still works on the desktop.

Python
import asyncio
import pygame

async def main():
    pygame.init()
    screen = pygame.display.set_mode((640, 480))
    clock = pygame.time.Clock()
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
        screen.fill("black")
        pygame.display.flip()
        clock.tick(60)
        await asyncio.sleep(0)   # hand control to the browser for this frame

    pygame.quit()

asyncio.run(main())

All game projects on this site use this form so you can play them in Pygame Online. Browser tools such as pygbag require it.

Fixed time steps (advanced)#

Delta time is enough for most games. Physics simulations sometimes need every step to be exactly the same length, so results don't change with frame rate. The usual technique is an accumulator: add each frame's time to a counter and run as many fixed-size steps as fit. The game physics tutorial shows a working example.

Common mistakes#

  • Calling clock.tick() twice per frame: each call waits again, halving your frame rate, and the second call returns a tiny dt.
  • Creating the Clock inside the loop: the new clock has no previous frame to measure against.
  • Moving in pixels per frame and also using dt: x += 5 * dt moves 5 pixels per second. Pick realistic per-second speeds such as 200–400.
  • Updating inside the event loop: code indented inside for event in ... runs once per event, not once per frame.

Practice exercises#

  1. Add a second box moving at 100 pixels per second and confirm both keep their speeds when you change the FPS cap.
  2. Make the box bounce between the window edges instead of wrapping.
  3. Print clock.get_fps() in the window caption every frame.
  4. Use the game loop generator to create a template with your own window size and options.
↑ ↓ to moveEnter to openEsc to close