Skip to content

Latest commit

 

History

History
383 lines (277 loc) · 8.66 KB

File metadata and controls

383 lines (277 loc) · 8.66 KB

Pygame Zero Setup Guide

Pygame Zero is a beginner-friendly game framework that makes it easy to create 2D games. This guide helps you install and run Pygame Zero games for weeks 13-18.

What is Pygame Zero?

  • Simplified version of Pygame (professional game library)
  • Perfect for learning game programming
  • No image assets required for our curriculum (we use shapes!)
  • Handles game loops, drawing, and input automatically

Option A: Install with Thonny (RECOMMENDED)

This is the easiest method for beginners.

Step 1: Open Thonny

Launch Thonny IDE (you should already have this from weeks 1-6).

Step 2: Install Pygame Zero

  1. Click ToolsManage packages...
  2. Type pgzero in the search box
  3. Click Search on PyPI
  4. Click Install next to "pgzero"
  5. Wait for installation to complete (may take 1-2 minutes)

Step 3: Test the installation

  1. Create a new file in Thonny
  2. Type this test program:
WIDTH = 400
HEIGHT = 300

def draw():
    screen.fill('blue')
    screen.draw.text('Pygame Zero works!', (100, 150), color='white')
  1. Save as test_pgzero.py
  2. Run it - you should see a blue window with white text!

If it works: ✅ You're ready for weeks 13-18!

If you see an error: Try Option B below.


Option B: Command Line Installation

For macOS:

Step 1: Open Terminal

  • Press Cmd+Space, type "Terminal", press Enter

Step 2: Install Pygame Zero

pip3 install pgzero

Step 3: Run games

cd /path/to/your/project/week13_pygamezero_setup
pgzrun week13.py

For Windows:

Step 1: Open Command Prompt

  • Press Windows key, type "cmd", press Enter

Step 2: Install Pygame Zero

pip install pgzero

Step 3: Run games

cd C:\path\to\your\project\week13_pygamezero_setup
pgzrun week13.py

Option C: Running from Python Code

If pgzrun command doesn't work, you can run Pygame Zero games directly from Python:

Add these lines to the END of your Pygame Zero file:

# Add at very end of file
import pgzrun
pgzrun.go()

Then run with regular Python:

python3 week13.py   # macOS/Linux
python week13.py    # Windows

Or run normally in Thonny with F5.


Option D: Browser-Based (No Installation)

If installation is difficult, you can use online Python environments:

Recommended Online Editors:

  1. Replit (replit.com)

    • Sign up for free account
    • Create new "Python" repl
    • Click "Packages" and add "pgzero"
    • Paste code and click "Run"
  2. Trinket.io (trinket.io)

    • Limited Pygame Zero support
    • Good for simple graphics
  3. PyCharm Edu (online version)

    • Full Python support
    • Can install packages

Note: Browser versions may have limitations (no sound, slower graphics). Desktop installation is preferred.


Troubleshooting

Problem: "pgzero module not found"

Solution 1: Install in correct Python version

# Find which Python Thonny uses
# In Thonny: Tools → Options → Interpreter
# Install pgzero for that Python version

# If Thonny uses Python 3.11:
python3.11 -m pip install pgzero

Solution 2: Use Thonny's package manager (Option A above)

Solution 3: Add to code (Option C above)


Problem: "pgzrun command not found"

Solutions:

  1. Use Option C: Add import pgzrun; pgzrun.go() to end of file
  2. Run directly: python3 -m pgzero week13.py
  3. Use Thonny to run (F5) after installing package

Problem: Window opens and closes immediately

Cause: Program finished too fast or error occurred

Solutions:

  1. Make sure you have draw() function defined
  2. Check for error messages in Thonny's output
  3. Don't use screen.mainloop() (Pygame Zero handles this)

Problem: "pygame.error: No available video device" (macOS)

Solution: XQuartz might be needed

# Install XQuartz
brew install --cask xquartz
# Log out and log back in
# Try running again

Or use Option D (browser-based).


Problem: Permission denied (macOS)

Solution: Allow Terminal/Thonny in Security settings

  1. System Settings → Privacy & Security
  2. Look for Terminal or Thonny in alerts
  3. Click "Allow" or "Open Anyway"
  4. Try again

Verifying Installation

Run this complete test program:

# test_pgzero_complete.py
WIDTH = 600
HEIGHT = 400

x = WIDTH // 2
y = HEIGHT // 2

def update():
    global x
    x = (x + 2) % WIDTH

def draw():
    screen.clear()
    screen.fill('darkblue')
    screen.draw.filled_circle((x, y), 20, 'yellow')
    screen.draw.text('Pygame Zero Working!', (180, 20), color='white')

def on_key_down(key):
    if key == keys.SPACE:
        print("Space pressed!")

Expected behavior:

  • Blue window appears
  • Yellow circle moves across screen
  • Pressing spacebar prints message
  • Window stays open until you close it

If this works perfectly: ✅ Everything is set up correctly!


Understanding Pygame Zero Structure

Pygame Zero games have a special structure:

# 1. CONFIGURATION (at top, outside functions)
WIDTH = 800    # Window width
HEIGHT = 600   # Window height

# 2. VARIABLES (game state)
score = 0
x = 100

# 3. UPDATE FUNCTION (called every frame)
def update():
    global x
    x = x + 1  # Update game state

# 4. DRAW FUNCTION (called every frame)
def draw():
    screen.clear()
    screen.fill('white')
    screen.draw.circle((x, 100), 25, 'red')

# 5. EVENT HANDLERS (optional)
def on_key_down(key):
    if key == keys.SPACE:
        print("Jump!")

# NO MAINLOOP NEEDED - Pygame Zero handles it!

Key Differences from Turtle

Feature Turtle Pygame Zero
Import import turtle No import needed
Screen setup screen = turtle.Screen() WIDTH = 800; HEIGHT = 600
Drawing t.forward(50) screen.draw.circle(...)
Game loop screen.mainloop() Automatic (define draw())
Animation Manual with ontimer Automatic (60 FPS)
Shapes Turtle shapes Any shape, any size
Performance Good for simple Great for complex games

Quick Reference: Essential Pygame Zero

Drawing:

def draw():
    screen.clear()
    screen.fill('blue')  # Background color
    screen.draw.circle((x, y), radius, 'red')
    screen.draw.filled_circle((x, y), radius, 'red')
    screen.draw.rect(Rect(x, y, width, height), 'green')
    screen.draw.line((x1, y1), (x2, y2), 'white')
    screen.draw.text('Hello', (x, y), color='white')

Updating:

def update():
    global x
    x = x + 1  # Update 60 times per second

Keyboard:

def on_key_down(key):
    if key == keys.UP:
        # Do something

Mouse:

def on_mouse_down(pos):
    x, y = pos
    print(f"Clicked at {x}, {y}")

Files Needed for Weeks 13-18

Good news: Our curriculum uses geometric shapes only - no image files needed!

All Pygame Zero examples use:

  • screen.draw.circle() instead of images
  • screen.draw.rect() for boxes
  • screen.draw.text() for score
  • Colors like 'red', 'blue', 'white'

This makes setup much simpler - just install Pygame Zero and you're ready!


Classroom Setup Tips

For Teachers:

  1. Test on one computer first before rolling out to class
  2. Use Thonny method - most reliable for students
  3. Have backup plan: Print code, demonstrate on projector
  4. Save working installation: Create USB stick with portable Thonny + pgzero
  5. Browser fallback: Have Replit accounts ready as backup

For Labs/Multiple Computers:

Create installation script:

# install_pgzero.sh (macOS/Linux)
#!/bin/bash
pip3 install pgzero
echo "Installation complete!"
python3 -c "import pgzero; print('Pygame Zero version:', pgzero.__version__)"
REM install_pgzero.bat (Windows)
pip install pgzero
echo Installation complete!
python -c "import pgzero; print('Pygame Zero installed!')"
pause

Still Having Problems?

Contact/Resources:

Alternative: Stick with Turtle

If Pygame Zero installation is impossible, you can adapt weeks 13-18 to use Turtle graphics instead. The concepts (game loops, collision, scoring) are the same!

See: docs/turtle_alternative_for_weeks_13-18.md (if needed, we can create this)


Success Checklist

Before starting Week 13:

  • Pygame Zero installed (test with simple program)
  • Can run programs from Thonny OR command line
  • Test program shows moving circle
  • Keyboard input works (spacebar test)
  • Understanding basic structure (WIDTH, draw(), update())

If all checked: ✅ Ready for Weeks 13-18 - let's make games!