Step by Step
Lesson 20 of 40 in Coddy's Make Games with Pygame course.
The snake always moves. Keep the way it is going in a direction: how many cells to add to the column and to the row in each step.
(1, 0)is right,(-1, 0)is left.(0, 1)is down,(0, -1)is up.
direction = (1, 0)
while running:
# events
head = (head[0] + direction[0], head[1] + direction[1])A tuple cannot be changed, so each step makes a new one. The clock runs at clock.tick(10): ten frames a second, so the snake moves ten cells a second.
Challenge
Easy- Before the loop, set
direction = (1, 0). - In the loop, after the events, move the head one step in
direction.
The snake leaves the window for now. Walls come later.
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)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
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