Menu
CoddyTech

Turn With the Arrows

Lesson 21 of 41 in Coddy's Make Games with Pygame course.

A snake turns once per key press, so read the arrows from KEYDOWN events. A dictionary maps each arrow key to its direction:

TURNS = {
    pygame.K_LEFT: (-1, 0),
    pygame.K_RIGHT: (1, 0),
    pygame.K_UP: (0, -1),
    pygame.K_DOWN: (0, 1),
}

event.key in TURNS is true for the four arrows, and TURNS[event.key] is the new direction. One test replaces four if statements:

elif event.type == pygame.KEYDOWN and event.key in TURNS:
    direction = TURNS[event.key]

Up is (0, -1): rows count down the window, like pixels.

challenge icon

Challenge

Easy

Steer the snake with the arrow keys.

  1. Above pygame.init(), add the TURNS dictionary for the four arrows.
  2. In the event loop, when a KEYDOWN event's key is in TURNS, set direction to its value.

Press Play and press Down: the snake turns down. Then Check.

Try it yourself

import pygame

CELL = 20
COLS, ROWS = 24, 18

pygame.init()
screen = pygame.display.set_mode((COLS * CELL, ROWS * CELL))
pygame.display.set_caption("Snake")
clock = pygame.time.Clock()


def draw_cell(cell, color):
    col, row = cell
    pygame.draw.rect(screen, color, (col * CELL + 1, row * CELL + 1, CELL - 2, CELL - 2))


head = (5, 9)
direction = (1, 0)

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

    head = (head[0] + direction[0], head[1] + direction[1])

    screen.fill((30, 30, 46))
    draw_cell(head, (180, 255, 160))
    pygame.display.flip()
    clock.tick(10)

pygame.quit()

All lessons in Make Games with Pygame

Practice on your own: Pygame playground