Turn With the Arrows
Lesson 21 of 40 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
Easy- Above
pygame.init(), add theTURNSdictionary for the four arrows. - In the event loop, when a KEYDOWN event's key is in
TURNS, setdirectionto its value.
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()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Make Games with Pygame
3Grids and Lists
A Grid of CellsStep by StepPractice on your own: Pygame playground