Pygame Snake, Pt. 1
Source: Dev.to
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 excellent project for beginners.
When using Pygame, each frame is drawn to an off‑screen buffer (an invisible canvas in memory). After the scene is assembled, the buffer is copied to the on‑screen canvas. Pygame also manages the event loop, allowing us to specify a target frames‑per‑second (FPS) and handling events such as key presses (KEYDOWN) and window closure (QUIT).
Minimal Pygame Setup
Below is a minimal Pygame program (adapted from the official documentation). It creates a 1000 × 1000 window, clears the screen each frame, and limits the loop to 20 FPS.
import pygame
# initialize pygame
pygame.init()
# create 1000x1000 pixel pygame window
screen = pygame.display.set_mode((1000, 1000))
# clock used to set FPS
clock = pygame.time.Clock()
# game runs as long as this is True
running = True
while running:
# poll for events
for event in pygame.event.get():
# pygame.QUIT = user closed window
if event.type == pygame.QUIT:
running = False
# fill buffer with white
screen.fill("white")
# copy buffer to screen
pygame.display.flip()
# limits FPS
clock.tick(20)
pygame.quit()
Note: The
runningflag is used to exit the loop cleanly when aQUITevent occurs. Python cannot break out of nested loops directly, so this pattern is common in Pygame programs.
Adding a Moving Square
To animate a square, we need a variable that tracks its position. Pygame provides a convenient Vector2 class for 2‑D coordinates.
-
Create a position vector just before the main loop:
dot = pygame.Vector2(500, 500) -
Update the position and draw the square inside the loop, after clearing the screen:
# fill buffer with white screen.fill("white") # move the square dot.x += 10 square = pygame.Rect(dot, (50, 50)) screen.fill("black", square)
The screen.fill("white") call clears the previous frame, and the three new lines draw a 50 × 50 black square at the updated coordinates.
Full Code with Moving Square
import pygame
# pygame setup
pygame.init()
screen = pygame.display.set_mode((1000, 1000))
clock = pygame.time.Clock()
running = True
# initial position of the square
dot = pygame.Vector2(500, 500)
while running:
# poll for events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# clear the screen
screen.fill("white")
# update position and draw the square
dot.x += 10
square = pygame.Rect(dot, (50, 50))
screen.fill("black", square)
# present the frame
pygame.display.flip()
# limit FPS
clock.tick(20)
pygame.quit()
Challenge
If you’re comfortable with Python, try extending the program:
- Add a check to see if
dot.xexceeds the window width (1000). - If it does, reset
dot.xto0so the square reappears on the left side after moving off the right edge.
dot.x += 10
if dot.x > 1000:
dot.x = 0