Menu
CoddyTech

The Clock

Lesson 4 of 40 in Coddy's Make Games with Pygame course.

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()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Make Games with Pygame

Practice on your own: Pygame playground