Menu
CoddyTech

The Clock

Lesson 4 of 41 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

Make the game run at 60 frames a second.

  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).

Press Play: the square looks the same, now drawn 60 times a second. Then Check.

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 Make Games with Pygame

Practice on your own: Pygame playground