Game Development 5 min read

Build a Classic Snake Game with Python and Pygame

This tutorial walks through creating a fully functional Snake game in Python using Pygame, covering window setup, snake and food initialization, directional controls, movement logic, collision detection, scoring, speed scaling, and game‑over conditions, all illustrated with code snippets and diagrams.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Build a Classic Snake Game with Python and Pygame

Game Initialization

The game window is set to 600×480 pixels and divided into a grid of 20×20‑pixel cells. The snake occupies three consecutive cells, the food occupies one cell placed randomly away from the snake, and variables for score, speed, and game state are initialized.

Direction and Scoring

The snake’s movement direction is stored as a 2‑D tuple (dx, dy) with four possible values: (1,0) right, (0,-1) down, (0,1) up, and (-1,0) left. Keyboard events (W/A/S/D or arrow keys) update this direction while preventing an immediate reversal.

p = (1,0) – move right

p = (0,-1) – move down

p = (0,1) – move up

p = (-1,0) – move left

for event in pygame.event.get():
    if event.type == QUIT:
        sys.exit()
    elif event.type == KEYDOWN:
        if event.key == K_RETURN:
            if game_over:
                start = True
                game_over = False
                b = True
                snake = init_snake()
                food = create_food(snake)
                food_style = get_food_style()
                pos = (1,0)
                score = 0
                last_move_time = time.time()
        elif event.key == K_SPACE:
            if not game_over:
                pause = not pause
        elif event.key in (K_w, K_UP):
            if b and not pos[1]:
                pos = (0,-1)
                b = False
        elif event.key in (K_s, K_DOWN):
            if b and not pos[1]:
                pos = (0,1)
                b = False
        elif event.key in (K_a, K_LEFT):
            if b and not pos[0]:
                pos = (-1,0)
                b = False
        elif event.key in (K_d, K_RIGHT):
            if b and not pos[0]:
                pos = (1,0)
                b = False

Snake Movement

The snake’s body coordinates are stored in a queue. Each frame removes the tail cell and inserts a new head cell based on the current direction, effectively moving the snake.

Eating Food

When the snake’s head reaches the food cell, the food is regenerated at a new random location, and the snake’s length grows by one cell (a new element is appended to the queue).

Scoring and Speed

The score increases by the food’s point value. Every 100 points, the snake’s speed is increased, making the game progressively harder.

score += food_style[0]
speed = orispeed - 0.03 * (score // 100)  # update speed

Game Over Conditions

The game ends when either the snake moves outside the window boundaries or the snake’s head collides with its own body. A boolean game_over flag tracks this state.

Overall, the tutorial demonstrates a complete, step‑by‑step implementation of the classic Snake game, suitable for beginners learning Python game development with Pygame.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Game DevelopmentTutorialSnake GamePygame
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.