Pygame Snake, Pt. 2

Published: (April 21, 2026 at 06:23 PM EDT)
2 min read
Source: Dev.to

Source: Dev.to

Introduction

In part 1 we set up a basic pygame window with a 1000 × 1000 pixel canvas and a 50 × 50 pixel square that moved continuously. For the snake game we want a fixed grid, so we’ll shrink the tiles and the canvas.

Updating Tile Size and Grid

We’ll use a 30 × 30 grid where each tile is 20 pixels square (30 tiles × 20 px = 600 px). Define three constants and replace all hard‑coded numbers with references to them:

W = 30   # grid width (tiles)
H = 30   # grid height (tiles)
S = 20   # tile size (pixels)

Create the screen using these values:

screen = pygame.display.set_mode((W * S, H * S))

Place the snake’s head (or “dot”) roughly in the centre of the grid:

dot = pygame.Vector2(W / 2, H / 2)

When drawing the square, scale the grid coordinates to pixel coordinates by multiplying by S:

square = pygame.Rect(dot * S, (S, S))

Add a wrap‑around check for the horizontal axis just before creating the square:

if dot.x > W:
    dot.x = 0

Full Code at This Point

import pygame

W = 30
H = 30
S = 20

# pygame setup
pygame.init()
screen = pygame.display.set_mode((W * S, H * S))
clock = pygame.time.Clock()
running = True

dot = pygame.Vector2(W / 2, H / 2)

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

    # fill buffer with white
    screen.fill("white")

    # move the dot to the right
    dot.x += 1
    if dot.x > W:
        dot.x = 0

    # draw the square (scaled to pixel size)
    square = pygame.Rect(dot * S, (S, S))
    screen.fill("black", square)

    # copy buffer to screen
    pygame.display.flip()

    # limit FPS
    clock.tick(20)

pygame.quit()

How the Scaling Works

The board is now a logical 30 × 30 grid of 1 × 1 tiles. When we draw, we scale those grid coordinates to actual pixel positions.

  • dot holds a grid coordinate, e.g., (15, 15).
  • Multiplying by S (dot * S) converts it to pixel space: (15 * 20, 15 * 20) = (300, 300).

Thus the square is drawn at the correct pixel location while we continue to think in terms of grid tiles.

0 views
Back to Blog

Related posts

Read more »

Pygame Snake, Pt. 1

Introduction Pygame is a module that lets us create 2D games with Python. It’s a great way to learn programming concepts, and the classic game Snake makes an e...

Pygame Snake, Pt. 3

Controlling the Square with Keyboard Input In Part 2 we had a square moving on a grid. Now we’ll make it respond to KEYDOWN events so the player can control it...