Build a Snake Game Using Python, Pygame | Step By Step Guide

Remember those old Nokia-style Snake games? Letโ€™s relive the nostalgia by building our very own Snake Game using Python and Pygame on your local system โ€” complete with UI, real-time score, and even sound effects!


Checkout Git Repo :- Click Here

๐Ÿ”ฐ What Weโ€™re Building

In this project, weโ€™ll recreate the iconic Snake Game with:

โœ… Fullscreen grid layout
โœ… Green snake & red food on a black screen
โœ… Score counter and Game Over screen
โœ… Sound effects when snake eats or dies
โœ… Easy controls with arrow keys

Itโ€™s fun, beginner-friendly, and perfect for brushing up on Python logic and game development skills!


โš™๏ธ Technologies & Tools Used

ToolPurpose
PythonProgramming language
PygameLibrary to create 2D games
VS CodeCode editor to write and run code
MP3/WAVAudio format for game sound effects

๐Ÿงฉ Python Modules Used โ€“ Explained

Letโ€™s understand the core modules used in this project:

1. pygame

The heart of the project. It helps create the window, handle input, draw shapes, control frame rate, play sounds, and render text.

Key submodules used:

  • pygame.display โ€“ Window creation and updates
  • pygame.draw โ€“ Draws snake blocks and food
  • pygame.time โ€“ Controls game speed (FPS)
  • pygame.event โ€“ Detects key presses and quit actions
  • pygame.font โ€“ Renders the score and messages
  • pygame.mixer โ€“ Plays sound effects (eating & game over)

2. random

Used to randomly generate the foodโ€™s position on the grid.

3. sys

Handles clean exit from the game.


Step-by-Step Guide to Build Snake Game in VS Code

โœ… Step 1: Create Project Folder

Create a folder named snake_game and open it in VS Code.

โœ… Step 2: Set Up Virtual Environment (venv)

In your terminal (inside VS Code):

python -m venv venv

Activate the environment:

  • Windows:
venv\Scripts\activate
  • Mac/Linux:
source venv/bin/activate

โœ… Step 3: Install Pygame

pip install pygame

โœ… Step 4: Add Sound Files

Place these two sound files in the same folder:

  • hiss.wav: plays when the snake eats food ( Click To Download )
  • gameover.wav: plays when the game ends ( Click To Download )

โœ… Step 5: Create snake_game_ui.py

Create a new Python file and paste the full game code:

import pygame
import random
import sys

# Initialize
pygame.init()
pygame.mixer.init()  # Initialize the sound system

# Load Sound Effects
eat_sound = pygame.mixer.Sound("hiss-86052.mp3")
gameover_sound = pygame.mixer.Sound("game-fail-90322.mp3")

# Screen Settings
WIDTH, HEIGHT = 800, 600
CELL_SIZE = 20

# Colors
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
DARK_GREEN = (0, 200, 0)
RED = (255, 0, 0)
WHITE = (255, 255, 255)

# Fonts
FONT = pygame.font.SysFont("consolas", 28, bold=True)
BIG_FONT = pygame.font.SysFont("consolas", 48, bold=True)

# Set up display
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("๐Ÿ Snake Game - Uday_Codes")

clock = pygame.time.Clock()
FPS = 10

# Helper function to draw text
def draw_text(surface, text, font, color, x, y):
    text_obj = font.render(text, True, color)
    surface.blit(text_obj, (x, y))

# Draw grid (optional for style)
def draw_grid():
    for x in range(0, WIDTH, CELL_SIZE):
        pygame.draw.line(screen, DARK_GREEN, (x, 0), (x, HEIGHT))
    for y in range(0, HEIGHT, CELL_SIZE):
        pygame.draw.line(screen, DARK_GREEN, (0, y), (WIDTH, y))

# Snake Game
def game_loop():
    # Snake setup
    snake = [[100, 100]]
    direction = [CELL_SIZE, 0]
    score = 0

    # Food setup
    food = [
        random.randint(0, (WIDTH - CELL_SIZE) // CELL_SIZE) * CELL_SIZE,
        random.randint(0, (HEIGHT - CELL_SIZE) // CELL_SIZE) * CELL_SIZE
    ]

    running = True
    while running:
        screen.fill(BLACK)
        draw_grid()

        # Events
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            # Controls
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP and direction[1] == 0:
                    direction = [0, -CELL_SIZE]
                elif event.key == pygame.K_DOWN and direction[1] == 0:
                    direction = [0, CELL_SIZE]
                elif event.key == pygame.K_LEFT and direction[0] == 0:
                    direction = [-CELL_SIZE, 0]
                elif event.key == pygame.K_RIGHT and direction[0] == 0:
                    direction = [CELL_SIZE, 0]

        # Move snake
        new_head = [snake[0][0] + direction[0], snake[0][1] + direction[1]]
        snake.insert(0, new_head)

        # Eat food
        if snake[0] == food:
            eat_sound.play()  # ๐Ÿ”Š Play eat sound
            score += 1
            food = [
                random.randint(0, (WIDTH - CELL_SIZE) // CELL_SIZE) * CELL_SIZE,
                random.randint(0, (HEIGHT - CELL_SIZE) // CELL_SIZE) * CELL_SIZE
            ]
        else:
            snake.pop()

        # Collision: Walls
        if (snake[0][0] < 0 or snake[0][0] >= WIDTH or
            snake[0][1] < 0 or snake[0][1] >= HEIGHT):
            return show_game_over(score)

        # Collision: Self
        if snake[0] in snake[1:]:
            return show_game_over(score)

        # Draw snake
        for block in snake:
            pygame.draw.rect(screen, GREEN, (block[0], block[1], CELL_SIZE, CELL_SIZE))

        # Draw food
        pygame.draw.rect(screen, RED, (food[0], food[1], CELL_SIZE, CELL_SIZE))

        # Draw Score
        draw_text(screen, f"Score: {score}", FONT, WHITE, 10, 10)

        pygame.display.update()
        clock.tick(FPS)

# Game Over Screen
def show_game_over(score):
    gameover_sound.play()  # ๐Ÿ”Š Play game over sound
    screen.fill(BLACK)
    draw_text(screen, "Game Over", BIG_FONT, RED, WIDTH//2 - 140, HEIGHT//2 - 80)
    draw_text(screen, f"Your Score: {score}", FONT, WHITE, WIDTH//2 - 100, HEIGHT//2 - 20)
    draw_text(screen, "Press R to Restart or Q to Quit", FONT, GREEN, WIDTH//2 - 190, HEIGHT//2 + 40)
    draw_text(screen, "Follow u_day_codes Instagram", FONT, GREEN, WIDTH//2 - 190, HEIGHT//2 + 80)
    pygame.display.update()

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    game_loop()
                elif event.key == pygame.K_q:
                    pygame.quit()
                    sys.exit()

# Start Game
game_loop()

โšก Make sure the sound files are in the same directory and your virtual environment is activated.

โœ… Step 6: Run the Game

python snake_game_ui.py

Enjoy the game! Control the snake using arrow keys. When the snake eats food, you’ll hear a hiss. When it crashes, a game over sound plays.

๐ŸŽฎ Controls

KeyAction
Arrow KeysMove the snake
RRestart game
QQuit game

Sound Effects

We used two .wav files: ( Download below Sound Effects from Google Drive and keep it in Your Project Folder [ Otherwise It Wont Work properly ])

  • hiss.wav: plays when the snake eats food ( Click To Download )
  • gameover.wav: plays when the game ends ( Click To Download )

Make sure these are short and optimized. You can trim silence and speed them up using tools like Audacity or pydub.

Final Output

You now have a fully working Snake Game that:

  • Runs smoothly in fullscreen
  • Tracks score
  • Detects wall/self collision
  • Plays audio effects
  • Looks super clean and retro!

๐Ÿ™Œ Conclusion

This Snake Game is an excellent beginner project to learn:

  • Game loops
  • Event handling
  • Collision logic
  • Working with sound and graphics

Itโ€™s minimal, fun, and instantly recognizable โ€” plus, you can customize it further by adding levels, background music, or cool themes.


If you liked this project, follow me on Instagram: [@u_day_codes]
And stay tuned for more such projects on udaycodes.in!

Leave a Comment