A Grid of Cells
Lesson 19 of 40 in Coddy's Make Games with Pygame course.
Snake moves on a grid. The window is 24 columns by 18 rows of cells, each 20 pixels square, and the snake moves one whole cell at a time.
Work in cells and turn them into pixels only to draw. Cell (col, row) starts at pixel (col * 20, row * 20). Drawing each cell 2 pixels smaller, 1 pixel in from each side, leaves a thin gap between neighbours so you can see the snake's segments.
def draw_cell(cell, color):
col, row = cell
pygame.draw.rect(screen, color, (col * CELL + 1, row * CELL + 1, CELL - 2, CELL - 2))col, row = cell unpacks the tuple into two variables. Keep the numbers in constants like CELL, COLS and ROWS: the code says what they mean, and changing one changes the whole game.
Challenge
Easy- Above the loop, write
draw_cell(cell, color), which draws one cell 1 pixel in from each side, as above. - Set
head = (5, 9). - After the fill, draw the head with
draw_cell(head, (180, 255, 160)).
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()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((30, 30, 46))
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