Skip to content

About

A feature-rich Python & Pygame arcade Snake game featuring dynamic power-ups, hard mode obstacles, local multiplayer, and persistent leaderboards.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

🐍 Snake Game — Classic Arcade with a Modern Twist

Python Pygame Architecture License

A feature-rich, object-oriented reimagining of the classic arcade Snake game built with Python and Pygame.
Featuring dynamic power-ups, teleporting obstacles, local multiplayer combat, persistent leaderboards, and fault-tolerant asset management.

Explore Features • Watch Demo • Game Modes • Architecture • Getting Started


📖 Table of Contents

  1. Overview
  2. Video Walkthrough
  3. Key Features
  4. Screenshots
  5. Game Modes
  6. Chance Box & Power-Ups
  7. Controls & Shortcuts
  8. Scoring & Progression
  9. Technical Architecture & OOP Design
  10. Project Structure
  11. Getting Started
  12. Future Roadmap
  13. License & Author

🌟 Overview

Snake Game goes far beyond the traditional retro grid experience. Developed as an Advanced Programming course project, it demonstrates clean Object-Oriented Programming (OOP), state-machine-driven game loops, real-time collision mathematics, and persistent JSON data storage.

Played on a $30 \times 30$ grid (with 20px cells yielding a crisp $600 \times 600$ playfield), players can test their reflexes solo across multiple difficulty tiers or challenge a friend in a local head-to-head battle.


🎬 Video Walkthrough

🎥 Live Gameplay Demonstration: Watch every game mode, power-up mechanic, and audio-visual effect in action below.

snake.mp4

✨ Key Features

  • 🍎 7 Randomized Fruits: Dynamic spawning of cherry, strawberry, apple, grapes, watermelon, mango, and lemon sprites—each extending the snake by +1 segment.
  • 🎁 Timed Chance Boxes: Mystery gift boxes spawn every 10 seconds, granting +20 points and triggering one of three game-changing power-ups.
  • 🧱 Dynamic Hard Mode: Introduces 10 deadly obstacle blocks that dynamically teleport to new coordinates every time a fruit is consumed.
  • 👥 Local Two-Player Arena: Competitive split-control multiplayer on a single keyboard.
  • ❤️ 3-Lives Respawn System: Single-player modes grant 3 lives; crashing respawns your snake at the center of the board while preserving your earned length.
  • 🚀 Progressive Speed Scaling: Base tick rate accelerates automatically for every 50 points scored.
  • 🏆 Persistent Hall of Fame: Top 10 unique player high scores are automatically serialized and saved to leaderboard.json (created automatically upon saving the first score).
  • 🛡️ Fault-Tolerant Asset Loader: Built-in fallback rendering and audio checks ensure the game never crashes if an image or sound file is missing from assets/.
  • 👀 Directional Rendering: Custom-drawn snake head featuring eyes that dynamically track the active movement vector.

📸 Screenshots

🖥️ Main Menu 🟢 Normal Mode
Main Menu Normal Gameplay
🔴 Hard Mode (Dynamic Obstacles) 👥 Two-Player Head-to-Head
Hard Mode Two Player Mode
🏆 Persistent Leaderboard
Leaderboard

🕹️ Game Modes

Mode Grid Size Lives Special Mechanics Win Condition Score Multiplier
🟢 Normal $30 \times 30$ 3 ❤️ Standard fruits & Chance Boxes Fill the entire 900-cell grid $1\times$
🔴 Hard $30 \times 30$ 3 ❤️ 10 Teleporting Obstacles relocate on every fruit eaten Reach 200 base points $3\times$ (on Leaderboard)
👥 Two-Player $30 \times 30$ 1 ⚡ Shared fruit; body-to-body & wall collision Outscore opponent before a crash occurs N/A (Versus Match)

🎁 Chance Box & Power-Ups

Every 10 seconds, a ChanceBox spawns on an unoccupied grid coordinate. Collecting it awards +20 points and activates one of three random abilities:

Power-Up Visual Cue (Snake Color) Duration Mechanical Effect
🛡️ Shield 🟣 Purple 5 seconds Grants full crash immunity and activates toroidal wrap-around (passing through one wall seamlessly exits from the opposite side).
🍒 Fruit Pack 🟢 Default Instant Immediately appends +5 body segments to the snake's tail.
⚡ Energy 🟠 Orange 5 seconds Doubles the active game loop frame rate ($2 \times \text{FPS}$) for high-speed maneuvering.

🎮 Controls & Shortcuts

📋 Main Menu Navigation

Key Action
1 Start Single-Player — Normal Mode
2 Start Single-Player — Hard Mode
3 Start Multiplayer — Two-Player Mode
4 View Hall of Fame (Leaderboard)
5 Exit Application

🕹️ In-Game Controls

Context Player Movement / Action Keys
Single-Player Solo Player W A S D or Arrow Keys
Two-Player 🔴 Player 1 (Red Snake) W (Up), S (Down), A (Left), D (Right)
Two-Player 🔵 Player 2 (Blue Snake) Arrow Keys (Up, Down, Left, Right)
Global Shortcut Pause / Resume Game P
While Paused Return to Main Menu M

🧮 Scoring & Progression

  • Eating a Fruit: +10 points (+1 segment length)
  • Collecting a Chance Box: +20 points (+ random power-up)
  • Speed Scaling Formula: The game starts at a base speed of 10 FPS and gains +1 FPS for every 50 points scored: $$\text{FPS} = 10 + \left\lfloor \frac{\text{Score}}{50} \right\rfloor$$
  • Hard Mode Fair Ranking: Because Hard Mode features shifting walls and ends at a 200-point cap, final scores are multiplied by 3 when recorded to the leaderboard.
  • Deduplicated Leaderboard: scoreboard.py ensures each player name holds only a single record—updating their entry only when they beat their personal best.

🏗️ Technical Architecture & OOP Design

The codebase is modularized into distinct single-responsibility components:

Module Class / Component Core Responsibilities & Technical Highlights
main.py Game Engine & State Machine Manages the Pygame event loop, frame timing (clock.tick(fps)), UI rendering, collision detection, and state transitions (menu, playing, paused, gameover, win, two_player). Uses Python 3.10+ structural pattern matching (match/case).
snake.py Snake Maintains an ordered list of $(x, y)$ grid tuples. Handles directional locking (preventing $180^\circ$ self-collision turns), head insertion, tail popping, and directional eye rendering.
food.py Food Spawns randomized fruit sprites across 7 fruit types while guaranteeing no overlap with existing snake segments. Implements defensive try/except image loading with a pygame.Surface fallback.
chance_box.py ChanceBox Manages cooldown timers (10s spawn cycle, 5s active buff timer) and tracks active power-up states (is_shield_active(), is_energy_active()), which main.py queries every frame. The Fruit Pack effect appends 5 segments directly to the snake's body.
obstacle.py Obstacle Generates and renders 10 collision hazards in Hard Mode, recalculating non-overlapping coordinates whenever food is consumed.
scoreboard.py Functions (save_score, get_top_scores) Handles file I/O with leaderboard.json, sorting entries in descending order and retaining the top 10 players.
sound.py Audio Manager Wraps pygame.mixer to trigger sound effects for eating, power-up collection, collisions, and victory screens with silent fallback support.

Key Algorithmic Details

  • Toroidal Grid Wrap-Around (Shield Mode): When the Shield buff is active, boundary collisions are bypassed using modulo arithmetic on the $30 \times 30$ coordinate space: $$(x_{\text{new}}, y_{\text{new}}) = \left( (x + \Delta x) \bmod 30,; (y + \Delta y) \bmod 30 \right)$$
  • Defensive Resource Management: Images in assets/ are loaded inside try/except blocks; if an image is missing, the engine dynamically generates a colored $20 \times 20\text{px}$ pygame.Surface in its place. Sound files are verified via os.path.exists, and missing audio files are gracefully skipped so gameplay is never interrupted.

🗂️ Project Structure

Snake-Game/
├── assets/                 # Sprites (7 fruits, gift box, heart) & WAV sound effects
├── screenshots/            # Gameplay captures for documentation
├── main.py                 # Entry point, state machine, collision engine, and UI screens
├── snake.py                # Snake entity class (movement vectors, growth, rendering)
├── food.py                 # Food entity class (7 fruit sprites, safe random spawning)
├── chance_box.py           # Mystery box timers and power-up state modifiers
├── obstacle.py             # Dynamic obstacle generator for Hard Mode
├── scoreboard.py           # JSON serialization and top-10 leaderboard logic
├── sound.py                # Fault-tolerant audio controller
├── requirements.txt        # Python package dependencies
├── .gitignore              # Ignores caches and the local leaderboard.json
├── LICENSE                 # MIT License file
└── README.md               # Project documentation

🚀 Getting Started

Prerequisites

  • Python 3.10 or higher (required for match/case syntax)
  • pip (Python package installer)
  • pygame (installed automatically in step 3 via requirements.txt)

Installation & Execution

  1. Clone the repository:

    git clone https://github.com/FarnazZS/Snake-Game.git
    cd Snake-Game
  2. Create and activate a virtual environment (optional but recommended):

    python -m venv .venv
    # On Windows:
    .venv\Scripts\activate
    # On macOS / Linux:
    source .venv/bin/activate
  3. Install dependencies:

    pip install -r requirements.txt
  4. Launch the game:

    python main.py

💡 Note: Always run python main.py from the root project directory so relative paths to assets/ and leaderboard.json resolve properly.


🔮 Future Roadmap

  • Integrate Chance Boxes into Two-Player mode for chaotic multiplayer battles
  • Add an in-game Settings Menu for audio volume sliders and custom keybindings
  • Implement Gamepad / Controller input support
  • Package standalone executables (.exe / .app) via PyInstaller

📄 License & Author

Distributed under the MIT License. See LICENSE for full details.

Developed by:
👩‍💻 Farnaz Zarrabi Shirabad — @FarnazZS

Built for the Advanced Programming Course (Project 3). If you enjoyed playing or found the code helpful, please consider giving this repository a ⭐!

About

A feature-rich Python & Pygame arcade Snake game featuring dynamic power-ups, hard mode obstacles, local multiplayer, and persistent leaderboards.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages