Menu
CoddyTech

Jump

Part of the Game Rules section of Coddy's Pygame journey. Lesson 24 of 29.

A jump is a speed upward that gravity takes away. Give the runner a vertical speed, vy. Each frame gravity adds 1 to it and the runner moves by it:

def update(self):
    self.vy += GRAVITY
    self.rect.y += self.vy
    if self.rect.bottom >= GROUND_Y:
        self.rect.bottom = GROUND_Y
        self.vy = 0

y grows downward, so a jump sets vy = -16: the runner rises 15 pixels, then 14, then 13, slows to a stop about 120 pixels up, and falls back faster and faster. When it reaches the ground line, it is put on it and stops.

Jump only from the ground. Without that test, every press in the air would start a new jump, and the runner could climb forever:

def jump(self):
    if self.rect.bottom == GROUND_Y:
        self.vy = -16

Section 5 builds on this with platforms to land on.

challenge icon

Challenge

Medium
  1. Add GRAVITY = 1, and self.vy = 0 to the runner.
  2. Write update() as shown and call runner.update() every frame, before drawing.
  3. Write jump(): vy = -16, only when the runner is on the ground.
  4. Space or Up calls runner.jump().

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


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


runner = Runner()

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))
    screen.blit(runner.image, runner.rect)
    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 Game Rules

Practice on your own: Pygame playground