Lazo Lab Sign up

App 6: Make a Game, Snake in Pygame / Build Snake

Lesson 5 of 10

Steering with arrow keys

Change direction on KEYDOWN events. Stop the snake turning straight back into itself.

Key points

  • event.key == pygame.K_UP
  • Ignore the exact opposite direction
  • Up is negative y
if event.type == pygame.KEYDOWN:
    new = {pygame.K_UP: (0, -1), pygame.K_DOWN: (0, 1),
           pygame.K_LEFT: (-1, 0), pygame.K_RIGHT: (1, 0)}.get(event.key)
    if new and (new[0] != -direction[0] or new[1] != -direction[1]):
        direction = new

Your turn

Add steering with the arrow keys.

Watch a video on thisOpens YouTube search results for “Steering with arrow keys” in a new tab

Quiz · +10 XP

In Pygame, which way does a negative y move?

Log in to save progress and earn XP.