Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 41 ยท Window, Loop and Events

The Game Loop

Build a correct Pygame game loop. Handle events, update, draw, cap the frame rate, move with delta time so speed is the same on every computer, and use a fixed time step.

The game loop is the heartbeat of every game. Each pass through it is one frame: read input, update the world, draw it. How you write this loop decides whether your game feels smooth, runs at the same speed on every machine and stays easy to extend. In this lesson you will write the standard loop, learn why frame rate matters, and then fix the classic bug where a game runs twice as fast on a faster computer.

The standard loop

Python
import pygame

pygame.init()
screen = pygame.display.set_mode((800, 450))
clock = pygame.time.Clock()
FPS = 60

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

    # 2. UPDATE
    update_game_state()

    # 3. DRAW
    screen.fill((0, 0, 0))
    draw_everything(screen)
    pygame.display.flip()

    # 4. WAIT
    clock.tick(FPS)

pygame.quit()

Keep the three jobs separate: do not move objects while handling events and do not change game state while drawing. When the phases are clean, you can pause the game by skipping only the update, or record a replay by saving only the events.

One frame, four steps

Events Read what the player did
Update Move, collide, score
Draw Clear, then paint
Wait clock.tick(60)

Repeat about 60 times per second.

1 / 2

Frame rate and clock.tick

clock.tick(60) pauses just long enough so the loop runs at most 60 times per second. Without it your loop runs as fast as the computer allows, hundreds of frames per second, using 100 percent of a CPU core and making the game speed depend on the hardware. The next lesson, Clock and Time, covers the clock in detail. Here we focus on what to do with its return value.

clock.tick() returns the number of milliseconds since the previous call. This is the frame time, usually called dt (delta time).

Frame-based versus time-based movement

Suppose a ball should cross the screen in about 4 seconds, and you write:

Python
x += 5          # pixels per FRAME

At 60 FPS the ball moves 300 pixels per second. On a slow computer that manages only 30 FPS, the ball moves 150 pixels per second: the game runs at half speed. The fix is to define speed in pixels per second and multiply by the time that actually passed:

Python
dt = clock.tick(60) / 1000      # seconds since last frame
x += 300 * dt                   # pixels per SECOND

Now both a 30 FPS and a 144 FPS machine move the ball 300 pixels per second. Let us prove it with a simulation.

Try it: frame speed versus delta time

This stand-in simulates three computers running at different frame rates for exactly one second of game time. It compares the distance moved with the "per frame" method and the "per second" method.

Python Why delta time matters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The naive column changes with the frame rate (150, 300, 720 pixels); the delta-time column is 300 every time.

Tip: Keep speeds in "units per second" in your constants (PLAYER_SPEED = 300) and multiply by dt once, inside the update. It also makes slow-motion trivial: multiply dt by 0.5.

Vectors make it neat

pygame.math.Vector2 works well for positions and velocities, because you can add and scale them as one unit. A Rect stores integers, so for smooth slow movement keep a float position and copy it into the rect for drawing:

Python
pos = pygame.Vector2(100, 200)
vel = pygame.Vector2(120, -40)       # pixels per second
...
pos += vel * dt
rect.center = pos

Try it: moving with a Vector2

Here is a bouncing ball in a box using vectors and delta time, simulated for a few frames at a fixed 50 ms step.

Python Vector movement with dt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A fixed time step

Variable dt has a weakness. If a frame takes unusually long (a window drag, a hiccup), one huge dt can make a character jump through a wall in a single step. Many games use a fixed time step: the simulation always advances in equal slices (say 1/60 s), and the loop runs as many slices as needed to catch up with real time. Rendering happens once per frame.

Python
STEP = 1 / 60
accumulator = 0.0

while running:
    frame_time = clock.tick() / 1000
    accumulator += min(frame_time, 0.25)     # clamp to avoid a spiral of death
    while accumulator >= STEP:
        update(STEP)
        accumulator -= STEP
    draw()

The clamp (0.25 seconds) stops the "spiral of death", where a slow frame causes many updates, which makes the next frame even slower.

Try it: fixed steps catching up

Pretend frames took different amounts of real time. The fixed-step loop always updates in identical slices, so the result is the same no matter how irregular the frames were.

Python Fixed time step with an accumulator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The position follows total time rather than the number of frames. Because every step has the same size, physics is also repeatable, which matters for game physics.

Quitting properly

Besides the close button, offer Escape or a menu entry. Do not call sys.exit() deep inside functions; set running = False and let the loop end so pygame.quit() runs. We will structure bigger games around this idea in the architecture chapter.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does clock.tick(60) return?

    It returns the elapsed milliseconds since the last call, which you divide by 1000 to get delta time in seconds.
  2. 2. Why does x += 5 per frame make a game run at different speeds on different computers?

    More frames per second means more additions per second. Multiplying a per-second speed by delta time removes the dependence.
  3. 3. What is the purpose of clamping the frame time in a fixed time step loop?

    Without a clamp, one very long frame leads to many updates, which takes even longer, and so on.
  4. 4. Which statement about the loop phases is best practice?

    Separate phases are easier to pause, test and reuse.

Summary

  • A frame is: events, update, draw, wait.
  • clock.tick(FPS) caps the speed and returns the frame time in milliseconds.
  • Express speeds in units per second and multiply by dt.
  • Use Vector2 for positions and velocities.
  • A fixed time step with an accumulator gives repeatable simulation; clamp the frame time.

Next: Clock and Time