The Runner
Part of the Game Rules section of Coddy's Pygame journey. Lesson 23 of 29.
This chapter builds Sky Runner, an endless runner. The runner stays near the left edge while obstacles come from the right; you jump over them for as long as you can. The sky and the ground are drawn. The runner is a sprite, as in section 3:
class Runner(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("assets/images/player.png").convert_alpha()
self.rect = self.image.get_rect(midbottom=(100, GROUND_Y))midbottom places the middle of the picture's bottom edge on a point. The runner's feet are at the bottom of its picture, so midbottom=(100, GROUND_Y) stands it on the ground at x 100, whatever its height.
GROUND_Y is the y of the ground's top edge, 260. Everything that stands on the ground uses it, so moving the ground later is one change.
Challenge
Easy- Write a
Runnersprite class whose image isassets/images/player.pngand whose rect has itsmidbottomat (100,GROUND_Y). - Make one, named
runner, before the loop. - Blit
runner.imageatrunner.rectafter drawing the ground.
Try it yourself
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 320))
pygame.display.set_caption("Sky Runner")
clock = pygame.time.Clock()
SKY = (140, 200, 240)
GROUND = (90, 160, 80)
GROUND_Y = 260
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill(SKY)
pygame.draw.rect(screen, GROUND, (0, GROUND_Y, 640, 60))
pygame.display.flip()
clock.tick(60)
pygame.quit()
All lessons in Game Rules
Practice on your own: Pygame playground