Snake
The classic: steer a growing snake around the board to eat pellets without biting your own tail.
- Difficulty
- Beginner
- Source size
- 171 lines, 1 file
- Requires
- Python 3.10+, pygame-ce or pygame
- Assets
- None (drawn in code)
Controls
- Arrow keys WASD Steer
- P Pause
- Space R Restart after game over
On this page
What you'll learn#
- Moving on a grid at a fixed step rate, independent of the frame rate
- Storing a body as a list of cells
- Buffering key presses so fast turns are never lost
- Placing food only on free cells
- Game states: playing, paused and game over
Run it on your computer#
- Install Python 3.10 or newer and Pygame:
python -m pip install pygame-ce(orpygame). See the installation guides. - Download snake.py into any folder.
- Open a terminal in that folder and run
python snake.py.
No images or sounds are needed: everything is drawn in code. The game also runs unchanged in Pygame Online, because its loop uses asyncio to hand control to the browser each frame.
How it works#
Moving on a grid#
The snake moves one cell at a time, but the game loop runs at 60 FPS. A timer accumulates dt, and the snake steps each time the timer passes step_time. Shortening step_time after each pellet makes the game speed up without changing the frame rate.
The body is a list#
self.body holds (column, row) tuples with the head first. Each step inserts a new head and removes the last cell, unless grow is above zero, in which case the tail stays and the snake gets longer. Self-collision is simply head in body[1:].
Buffered turns#
If you press Up then Left within one step, a naive game only sees the last key. Snake.turn() queues up to three turns and ignores direct reversals (pressing Left while moving Right), which would instantly kill the snake.
Wrap-around#
(x + dx) % COLS sends the snake out one side and in the other. To make walls deadly instead, end the game when the new head is outside the board.
Complete source code#
"""Snake - a Pygame.net game project.
Steer the snake, eat the yellow pellets and avoid running into yourself.
The snake wraps around the edges of the board.
Run it: pip install pygame-ce (or: pip install pygame)
python snake.py
Controls: Arrow keys or WASD to steer, P to pause, Space or R to restart.
License: MIT - https://pygame.net/licenses/
"""
import asyncio
import random
import pygame
CELL = 20
COLS, ROWS = 32, 22
HUD = 40
WIDTH, HEIGHT = COLS * CELL, ROWS * CELL + HUD
FPS = 60
BG = (16, 26, 48)
GRID = (24, 37, 64)
SNAKE = (91, 147, 230)
HEAD = (157, 194, 255)
FOOD = (244, 197, 49)
TEXT = (230, 236, 247)
DIRECTIONS = {
pygame.K_UP: (0, -1), pygame.K_w: (0, -1),
pygame.K_DOWN: (0, 1), pygame.K_s: (0, 1),
pygame.K_LEFT: (-1, 0), pygame.K_a: (-1, 0),
pygame.K_RIGHT: (1, 0), pygame.K_d: (1, 0),
}
class Snake:
def __init__(self):
mid = (COLS // 2, ROWS // 2)
self.body = [mid, (mid[0] - 1, mid[1]), (mid[0] - 2, mid[1])]
self.direction = (1, 0)
self.queued = [] # buffered turns so quick key presses are not lost
self.grow = 0
@property
def head(self):
return self.body[0]
def turn(self, new_dir):
last = self.queued[-1] if self.queued else self.direction
# Ignore reversing straight into the neck and duplicate presses.
if new_dir != last and (new_dir[0] + last[0], new_dir[1] + last[1]) != (0, 0):
if len(self.queued) < 3:
self.queued.append(new_dir)
def step(self):
if self.queued:
self.direction = self.queued.pop(0)
x, y = self.head
dx, dy = self.direction
new_head = ((x + dx) % COLS, (y + dy) % ROWS)
self.body.insert(0, new_head)
if self.grow > 0:
self.grow -= 1
else:
self.body.pop()
def hit_self(self):
return self.head in self.body[1:]
class Game:
def __init__(self, seed=None):
self.rng = random.Random(seed)
self.font = pygame.font.Font(None, 30)
self.big = pygame.font.Font(None, 64)
self.best = 0
self.reset()
def reset(self):
self.snake = Snake()
self.score = 0
self.step_time = 0.12 # seconds per move; shrinks as you score
self.timer = 0.0
self.state = "playing" # playing, paused, over
self.food = self.place_food()
def place_food(self):
free = [(c, r) for c in range(COLS) for r in range(ROWS) if (c, r) not in self.snake.body]
return self.rng.choice(free)
def handle_event(self, event):
if event.type != pygame.KEYDOWN:
return
if self.state == "over" and event.key in (pygame.K_SPACE, pygame.K_r, pygame.K_RETURN):
self.reset()
elif event.key == pygame.K_p and self.state != "over":
self.state = "paused" if self.state == "playing" else "playing"
elif event.key in DIRECTIONS and self.state == "playing":
self.snake.turn(DIRECTIONS[event.key])
def update(self, dt):
if self.state != "playing":
return
self.timer += dt
while self.timer >= self.step_time:
self.timer -= self.step_time
self.snake.step()
if self.snake.hit_self():
self.state = "over"
self.best = max(self.best, self.score)
return
if self.snake.head == self.food:
self.score += 1
self.snake.grow += 2
self.step_time = max(0.055, self.step_time * 0.97)
self.food = self.place_food()
def draw(self, surface):
surface.fill(BG)
for c in range(COLS):
for r in range(ROWS):
if (c + r) % 2 == 0:
surface.fill(GRID, (c * CELL, HUD + r * CELL, CELL, CELL))
fx, fy = self.food
pygame.draw.rect(surface, FOOD, (fx * CELL + 4, HUD + fy * CELL + 4, CELL - 8, CELL - 8), border_radius=3)
for i, (x, y) in enumerate(self.snake.body):
color = HEAD if i == 0 else SNAKE
pygame.draw.rect(surface, color, (x * CELL + 1, HUD + y * CELL + 1, CELL - 2, CELL - 2), border_radius=4)
pygame.draw.rect(surface, (11, 18, 34), (0, 0, WIDTH, HUD))
surface.blit(self.font.render(f"Score {self.score}", True, TEXT), (14, 11))
best = self.font.render(f"Best {self.best}", True, TEXT)
surface.blit(best, (WIDTH - best.get_width() - 14, 11))
if self.state == "paused":
self.banner(surface, "Paused", "Press P to continue")
elif self.state == "over":
self.banner(surface, "Game over", "Press Space to play again")
def banner(self, surface, title, hint):
shade = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
shade.fill((0, 0, 0, 150))
surface.blit(shade, (0, 0))
t = self.big.render(title, True, FOOD)
h = self.font.render(hint, True, TEXT)
surface.blit(t, t.get_rect(center=(WIDTH // 2, HEIGHT // 2 - 20)))
surface.blit(h, h.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 30)))
async def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake - Pygame.net")
clock = pygame.time.Clock()
game = Game()
running = True
while running:
dt = clock.tick(FPS) / 1000
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
else:
game.handle_event(event)
game.update(dt)
game.draw(screen)
pygame.display.flip()
await asyncio.sleep(0) # lets the browser draw when running on the web
pygame.quit()
if __name__ == "__main__":
asyncio.run(main())The code is released under the MIT license: use it, change it and build on it. See licenses.
Ideas to extend it#
- Make the walls deadly instead of wrapping.
- Add a golden pellet that appears briefly and is worth five points.
- Save the best score with the score system technique.
- Add a second snake for a two-player mode controlled with WASD.
- Draw the snake's head with eyes that face the direction of travel.