Menu
CoddyTech

Sprint

Lesson 6 of 40 in Coddy's Make Games with Pygame course.

A variable can change every frame, depending on what the player does. Here the speed depends on whether Space is held.

keys = pygame.key.get_pressed()
speed = 4
if keys[pygame.K_SPACE]:
    speed = 8

Every frame starts from the normal speed, 4. Only a frame where Space is down raises it to 8. Let go of Space and the next frame is back to 4.

Set the normal value first and the special one after it. In the other order the second line always wins and Space does nothing.

challenge icon

Challenge

Easy

Let the player sprint:

  1. Remove speed = 4 from above the loop.
  2. In the loop, right after keys = pygame.key.get_pressed(), set speed = 4, then set it to 8 if Space is held.

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Move the Square")
clock = pygame.time.Clock()

x, y = 220, 160
speed = 4

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

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        x -= speed
    if keys[pygame.K_RIGHT]:
        x += speed
    if keys[pygame.K_UP]:
        y -= speed
    if keys[pygame.K_DOWN]:
        y += speed

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (255, 196, 0), (x, y, 40, 40))
    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 Make Games with Pygame

Practice on your own: Pygame playground