A Frame Counter
Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 27 of 39.
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
MediumMake the character walk.
- Before the loop, make
frame_index = 0andtimer = 0. - Each frame, add 1 to
timer; at 10, set it back to 0 and moveframe_indexon, wrapping with% len(frames). - Draw
frames[frame_index]at(x, 300).
Press Play: the character's legs move as it walks. Then Check.
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()
All lessons in Sprites and Images
Practice on your own: Pygame playground