Menu
CoddyTech

The Clock

Part of the The Game Loop section of Coddy's Pygame journey. Lesson 4 of 32.

Your loop runs as fast as the computer can go: thousands of frames a second on a fast machine, fewer on a slow one. A game needs the same speed everywhere.

A pygame.time.Clock keeps the pace. Make one before the loop, then call clock.tick(60) once at the end of each pass. It waits as long as needed so the loop runs at most 60 times a second.

clock = pygame.time.Clock()

running = True
while running:
    # events, drawing, flip
    clock.tick(60)

60 frames a second is the usual rate for smooth movement. From now on, something that moves 4 pixels each frame moves 240 pixels each second.

challenge icon

Challenge

Easy
  1. Below the set_caption line, make a clock: clock = pygame.time.Clock().
  2. As the last line of the loop, after the flip, call clock.tick(60).

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Move the Square")

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

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (255, 196, 0), (220, 160, 40, 40))
    pygame.display.flip()

pygame.quit()

All lessons in The Game Loop

Practice on your own: Pygame playground