Menu
CoddyTech

A Frame Counter

Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 26 of 36.

The character walks across the window, but its legs never move: it always shows frames[0]. Showing the other frame each time would flicker 60 times a second, far too fast for legs. Hold each picture for a few frames instead, with a counter:

timer += 1
if timer == 10:
    timer = 0
    frame_index = (frame_index + 1) % len(frames)

timer counts frames. Every 10 frames it starts again at 0 and frame_index moves on to the next picture. % len(frames) wraps it back to 0 after the last one, so the walk loops forever, whatever the number of frames in the list.

Draw frames[frame_index]. At 60 frames a second each pose shows for a sixth of a second: a calm walk. A smaller number than 10 makes the legs move faster.

challenge icon

Challenge

Medium
  1. Before the loop, make frame_index = 0 and timer = 0.
  2. Each frame, add 1 to timer; when it reaches 10, set it back to 0 and move frame_index to the next frame, wrapping with % len(frames).
  3. Draw frames[frame_index] at (x, 300).

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Walk Cycle")
clock = pygame.time.Clock()

sheet = pygame.image.load("assets/sheets/platformer_characters.png").convert_alpha()
frames = []
for col in (0, 1):
    frame = sheet.subsurface((col * 24, 0, 24, 24))
    frames.append(pygame.transform.scale_by(frame, 3))
x = 0

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

    x += 2
    if x > 640:
        x = -72

    screen.fill((20, 22, 40))
    screen.blit(frames[0], (x, 300))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
quiz iconTest yourself

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

All lessons in Sprites and Images

Practice on your own: Pygame playground