DEV Community

Cover image for How I Built a Snake Game Using Amazon Q CLI: A Step-by-Step Tutorial
Zaynul Abedin Miah
Zaynul Abedin Miah

Posted on

2

How I Built a Snake Game Using Amazon Q CLI: A Step-by-Step Tutorial

The classic Snake game brings back memories of guiding a pixelated snake to gobble up food while dodging collisions. I wanted to recreate this nostalgic game with modern twists—multiple difficulty levels, power-ups, obstacles, visual effects, and sound—all built from scratch using Amazon Q CLI, an AI-powered command-line tool that generates code, debugs issues, and automates tasks through natural language prompts. In this tutorial, I’ll share how I developed an Enhanced Snake Game in Python using Pygame, with Amazon Q CLI as my coding partner. Whether you’re a beginner or a seasoned coder, this guide will show you how to leverage AI to create a fun, feature-rich game.

Background and Context

The Enhanced Snake Game is a modern take on the classic arcade game, built using Python and Pygame in a WSL2 environment. The project leveraged Amazon Q CLI, a generative AI-powered command-line tool that supports natural language code generation, debugging, and automation. The user’s journey involved initiating Amazon Q CLI, generating the base game, iteratively adding features, and resolving technical challenges, resulting in a polished game with advanced mechanics.

The Enhanced Snake Game that we are going to build using Amazon Q CLI includes:

  • Multiple Difficulty Levels: Easy, Medium, Hard, and Extreme, with varying speeds and wall collision options.
  • Special Food and Power-Ups: Bonus food for extra points, plus speed boosts, invincibility, and double-score effects.
  • Obstacles: Randomly placed blocks that challenge navigation.
  • Visual Effects: Particle explosions when collecting items and pulsating effects for special food and power-ups.
  • Sound Effects: Audio cues for eating, power-ups, and game over, plus background music.
  • Persistent High Scores: Saved in a JSON file for each difficulty level.
  • By the end, you’ll have a polished game and a clear understanding of how Amazon Q CLI can accelerate development.
    Prerequisites
    Before diving in, ensure you have:

  • Amazon Q CLI: Installed on your system (instructions below).

  • Python 3: Installed, along with the Pygame library (pip install pygame).

  • AWS Builder ID: Required to use Amazon Q CLI for free. Sign up at AWS Builder ID. Or use pro license if you have that would be great.

  • WSL2: For Windows users, or a Linux/macOS environment.

  • Basic Python knowledge (though Amazon Q CLI simplifies much of the coding).
    Step 1: Setting Up Amazon Q CLI
    But as I'm using windows so to start, I set up Amazon Q CLI in my Windows Subsystem for Linux (WSL2) environment on Windows, which provides a Linux-like setup for running the tool. Here’s how to do it:

Open a WSL Terminal:

Launch WSL by running

wsl -d Ubuntu
Enter fullscreen mode Exit fullscreen mode

in a Windows Command Prompt or PowerShell.

Install Dependencies:

Ensure curl and unzip are installed

:sudo apt update
sudo apt install curl unzip
Enter fullscreen mode Exit fullscreen mode

Download and Install Amazon Q CLI:

Download the zip

file:curl --proto '=https' --tlsv1.2 -sSf https://desktop-release.q.us-east-1.amazonaws.com/latest/q-x86_64-linux.zip -o q.zip
Enter fullscreen mode Exit fullscreen mode

Unzip and install:

unzip q.zip
./q/install.sh

Enter fullscreen mode Exit fullscreen mode

Log In with AWS Builder ID:

Run:q login

Select “Use for Free with Builder ID,” follow the browser prompts to sign in, and complete the authentication.

Verify Installation:

Check if Amazon Q CLI is working

:q doctor
Enter fullscreen mode Exit fullscreen mode

If it outputs “Everything looks good!” you’re ready to go.
Image description

With Amazon Q CLI set up, I was ready to start coding.
Step 2: Creating the Base Snake Game
I began by creating a basic Snake game using Pygame. In the WSL terminal, I started Amazon Q CLI’s chat feature:
q chat

I entered this prompt:
Create a basic Snake game in Python using Pygame. The snake should move with arrow keys, grow when it eats food, and end if it hits the wall or itself.

Amazon Q CLI generated a working game, which I saved as simple_snake_game.py. You can check out the repository here for the code it generated.

Image description

This code created a simple Snake game where the snake moves, eats food to grow, and ends on wall or self-collision. I tested it by running:
python3 simple_snake_game.py

Step 3: Adding Difficulty Levels
To make the game more engaging, I added difficulty levels. I prompted Amazon Q CLI:
Add difficulty levels to the Snake game: Easy (slow speed, screen wrap), Medium (medium speed, screen wrap), Hard (fast speed, wall collision), and Extreme (very fast, wall collision). Include a menu to select the difficulty.

Amazon Q CLI generated code with a difficulty dictionary and a menu system. Here’s a snippet:

DIFFICULTY_LEVELS = {
    "Easy": {"speed": 8, "color": (0, 255, 0), "wall_collision": False},
    "Medium": {"speed": 12, "color": (0, 0, 255), "wall_collision": False},
    "Hard": {"speed": 16, "color": (255, 0, 0), "wall_collision": True},
    "Extreme": {"speed": 20, "color": (255, 255, 0), "wall_collision": True}
}

def show_difficulty_menu():
    selected = 0
    options = list(DIFFICULTY_LEVELS.keys())
    while True:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    selected = (selected - 1) % len(options)
                elif event.key == pygame.K_DOWN:
                    selected = (selected + 1) % len(options)
                elif event.key == pygame.K_RETURN:
                    return options[selected]
        screen.fill((0, 0, 0))
        for i, option in enumerate(options):
            color = DIFFICULTY_LEVELS[option]["color"] if i == selected else (255, 255, 255)
            text = font.render(option, True, color)
            screen.blit(text, (WIDTH // 2 - text.get_width() // 2, 200 + i * 50))
        pygame.display.flip()
        clock.tick(10)

Enter fullscreen mode Exit fullscreen mode

This added a menu where players select difficulty, and the game adjusts speed and wall behavior accordingly.

Image description

**Step 4: Adding Special Food and Power-Ups
**To increase excitement, I added special food and power-ups. My prompt:
Add special food that gives bonus points and disappears after a few seconds. Include power-ups like speed boost, invincibility, and double score that spawn randomly.

Amazon Q CLI created Food and PowerUp classes:

class Food:
    def __init__(self):
        self.position = (0, 0)
        self.type = "normal"  # normal, bonus, or special
        self.color = RED
        self.points = 1
        self.spawn_time = pygame.time.get_ticks()
        self.lifespan = None  # None means permanent
        self.randomize_position()

Enter fullscreen mode Exit fullscreen mode

class PowerUp:
    def __init__(self):
        self.position = (0, 0)
        self.active = False
        self.type = None
        self.spawn_time = 0
        self.lifespan = 10000  # 10 seconds

Enter fullscreen mode Exit fullscreen mode

These classes enabled dynamic food types and power-ups with timed effects, enhancing gameplay strategy.
**Step 5: Introducing Obstacles
**To add challenge, I included obstacles. I prompted:
Add randomly placed obstacles that the snake must avoid unless it’s invincible.

Image description

Amazon Q CLI generated an Obstacle class:

class Obstacle:
    def __init__(self):
        self.positions = []
        self.generate()

    def generate(self):
        self.positions = []
        # Create 5-10 random obstacles
        num_obstacles = random.randint(5, 10)
        for _ in range(num_obstacles):
            pos = (random.randint(2, GRID_WIDTH - 3), random.randint(2, GRID_HEIGHT - 3))
            # Make sure obstacles aren't too close to the center where the snake starts
            if abs(pos[0] - GRID_WIDTH // 2) > 3 or abs(pos[1] - GRID_HEIGHT // 2) > 3:
                self.positions.append(pos)
Enter fullscreen mode Exit fullscreen mode

This added random blocks, making navigation trickier unless the snake was invincible.
Step 6: Enhancing Visual Effects
For a polished look, I added visual effects. My prompt:
Add particle effects when the snake eats food or collects a power-up. Make special food and power-ups pulsate.

Amazon Q CLI provided a Particle class and pulsating effects:

# Particle effect class
class Particle:
    def __init__(self, x, y, color):
        self.x = x
        self.y = y
        self.color = color
        self.size = random.randint(2, 5)
        self.life = 30
        self.vx = random.uniform(-1, 1)
        self.vy = random.uniform(-1, 1)
Enter fullscreen mode Exit fullscreen mode

This created engaging visuals, like explosions and pulsating items.

Step 7: Adding Sound Effects
To enhance immersion, I added sound. My prompt:
Add sound effects for eating food, collecting power-ups, and game over. Include background music.

Amazon Q CLI generated code to load audio files:

    eat_sound = try_load_sound("eat.wav")
    if eat_sound is None:
        eat_sound = try_load_sound("eat.mp3")

    # Load game over sound
    game_over_sound = try_load_sound("game_over.wav")
    if game_over_sound is None:
        game_over_sound = try_load_sound("game_over.mp3")

    # Load powerup sound
    powerup_sound = try_load_sound("powerup.wav")
    if powerup_sound is None:
        powerup_sound = try_load_sound("powerup.mp3")

    # Set maximum volume for all sounds
    if eat_sound:
        eat_sound.set_volume(1.0)
        print("Eat sound volume set to maximum")
    if game_over_sound:
        game_over_sound.set_volume(1.0)
        print("Game over sound volume set to maximum")
    if powerup_sound:
        powerup_sound.set_volume(1.0)
        print("Power-up sound volume set to maximum")

Enter fullscreen mode Exit fullscreen mode

I downloaded eat.wav, game_over.wav, powerup.wav, and background.mp3 from pixabay and placed them in /home/q/snake_game_assets/sounds.

Image description
Step 8: High Score Tracking
To keep players engaged, I added persistent high scores. My prompt:
Add high score tracking that saves to a JSON file for each difficulty.

Amazon Q CLI implemented:

    def load_high_scores(self):
        try:
            highscore_file = os.path.join(DEFAULT_ASSETS_DIR, "highscores.json")
            if os.path.exists(highscore_file):
                with open(highscore_file, 'r') as f:
                    return json.load(f)
            return {"Easy": 0, "Medium": 0, "Hard": 0, "Extreme": 0}
        except:
            print("Error loading high scores")
            return {"Easy": 0, "Medium": 0, "Hard": 0, "Extreme": 0}

    def save_high_scores(self):
        try:
            highscore_file = os.path.join(DEFAULT_ASSETS_DIR, "highscores.json")
            os.makedirs(os.path.dirname(highscore_file), exist_ok=True)
            with open(highscore_file, 'w') as f:
                json.dump(self.high_scores, f)
        except:
            print("Error saving high scores") f)
Enter fullscreen mode Exit fullscreen mode

This saved scores to highscores.json in the assets directory.

Image description

Step 9: Polishing and Debugging
I polished the game with features like pause (P key), wall toggle (W key), and dynamic difficulty switching (1-4 keys). I faced challenges like:

Sound Loading Issues: Files were initially in the wrong directory (/home/q/sounds). I moved them to /home/q/snake_game_assets/sounds.
WSL Path Issues: Fixed by using os.path for cross-platform compatibility.
Double File Extensions: Renamed files like eat.wav.wav to eat.wav.

Amazon Q CLI helped debug these by suggesting path fixes and creating a sound test script.

Conclusion
Using Amazon Q CLI, I transformed a simple idea into a feature-rich Enhanced Snake Game in just a few hours. The AI’s ability to generate code, debug issues, and explain concepts made development fast and educational. Try it yourself at AWS Builder ID and start building your own games!

Image description

Warp.dev image

The best coding agent. Backed by benchmarks.

Warp outperforms every other coding agent on the market, and gives you full control over which model you use. Get started now for free, or upgrade and unlock 2.5x AI credits on Warp's paid plans.

Download Warp

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

Feature flag article image

Create a feature flag in your IDE in 5 minutes with LaunchDarkly’s MCP server 🏁

How to create, evaluate, and modify flags from within your IDE or AI client using natural language with LaunchDarkly's new MCP server. Follow along with this tutorial for step by step instructions.

Read full post

👋 Kindness is contagious

Delve into a trove of insights in this thoughtful post, celebrated by the welcoming DEV Community. Programmers of every stripe are invited to share their viewpoints and enrich our collective expertise.

A simple “thank you” can brighten someone’s day—drop yours in the comments below!

On DEV, exchanging knowledge lightens our path and forges deeper connections. Found this valuable? A quick note of gratitude to the author can make all the difference.

Get Started