Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 41 ยท Packaging and Next Steps

Packaging and Sharing Your Pygame Game

Turn a Pygame project into something others can play: asset paths that survive packaging, PyInstaller executables, web builds with pygbag, checklists and publishing on itch.io.

A game that only runs from your terminal is not finished. Your friends will not install Python, create a virtual environment and type python main.py; they want to double-click a file or open a web page. Packaging turns your project into something people can run, and publishing puts it where they can find it.

This lesson walks through preparing your code, building a standalone program with PyInstaller, making a browser version with pygbag, testing the result and sharing it. The commands run in your own terminal (they cannot run here), but the path-handling and checklist logic is runnable.

Step 1: make the project packageable

Before you build anything, fix the things that break most often.

Paths. A packaged game does not run from your project folder. PyInstaller's single-file mode unpacks assets into a temporary directory at launch, so relative paths such as "assets/ship.png" fail. Use one helper everywhere:

Python
import sys
from pathlib import Path

def resource_path(relative):
    base = Path(getattr(sys, "_MEIPASS", Path(__file__).parent))
    return base / relative

ship = pygame.image.load(resource_path("assets/images/ship.png"))

sys._MEIPASS exists only inside a PyInstaller bundle; otherwise the code uses the folder of the script. Saves and settings must not use this folder; keep them in a per-user folder as in Saving High Scores and Settings.

Python Resolve asset paths in both modes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Dependencies. Create a requirements.txt, pinning versions for reproducible builds:

TEXT
pygame-ce==2.5.*

Entry point and window. Keep main.py tiny (see Organizing Pygame Code), set a window title and icon with pygame.display.set_caption and set_icon, and make sure quitting works with the window's close button and Esc.

Errors. Wrap the top level so that a crash shows a message and writes a log, instead of a console window that disappears:

Python
import logging, traceback
logging.basicConfig(filename=str(save_dir("MyGame") / "crash.log"), level=logging.INFO)

try:
    Game().run()
except Exception:
    logging.exception("The game crashed")
    raise

Step 2: build a desktop program with PyInstaller

PyInstaller bundles your script, the Python interpreter, Pygame and your assets into a folder or a single executable. Install it in your virtual environment and build:

Terminal
pip install pyinstaller
pyinstaller --noconsole --onefile --name SpaceGardeners \
  --icon assets/icon.ico \
  --add-data "assets;assets" \
  main.py
  • --noconsole (or --windowed) hides the black terminal window.
  • --onefile creates one executable; omit it for a folder, which starts faster and is easier to debug.
  • --add-data "source;destination" copies assets. On Windows the separator is ;, on macOS and Linux it is :.
  • --icon sets the file icon (.ico on Windows, .icns on macOS).

The result lands in dist/. PyInstaller builds for the system it runs on only, so build the Windows version on Windows, the macOS one on a Mac and the Linux one on Linux. A free way to do this is a CI workflow (for example GitHub Actions with a matrix of three operating systems).

Once you tweak many options, PyInstaller writes a .spec file. Edit it and rebuild with pyinstaller SpaceGardeners.spec, so the command is repeatable.

flowchart LR
  A["main.py + assets"] --> B["PyInstaller analysis<br/>(finds imports)"]
  B --> C["bundle: Python + pygame + assets"]
  C --> D["dist/SpaceGardeners.exe"]
  D --> E["zip and share"]

PyInstaller follows your imports, collects what they need and wraps it into one launcher.

Troubleshooting a build

Problem Fix
Game opens and closes immediately Build without --noconsole, run from a terminal to read the error
FileNotFoundError for assets Use resource_path and check --add-data separators
Missing module Add --hidden-import module_name
Antivirus warns about the exe Common with --onefile; sign the file or ship a folder build and submit a false-positive report
Huge file size Use a clean virtual environment containing only what you need
Slow start Use the folder build; one-file mode unpacks on every launch

Alternatives worth knowing: Nuitka compiles Python to C for speed and often smaller exes; cx_Freeze and Briefcase (for installers and mobile) suit other workflows.

Step 3: a web version with pygbag

Many players will try a game in a browser tab but will not download an unknown executable. pygbag compiles your Pygame game to WebAssembly so it runs on a web page.

Terminal
pip install pygbag
pygbag mygame            # builds and serves on http://localhost:8000
pygbag --build mygame    # builds the upload folder: mygame/build/web

The browser has rules that your desktop game ignores:

  • The main loop must be async and call await asyncio.sleep(0) once per frame, so the browser can breathe.
  • Your entry file must be named main.py.
  • Use OGG for audio (WAV for short effects works too); MP3 is not portable.
  • No blocking calls (time.sleep, input()), and no threads.
  • Files cannot be saved to a normal folder; use the browser's storage through the platform helpers or just do without.
Python
import asyncio
import pygame

async def main():
    pygame.init()
    screen = pygame.display.set_mode((960, 540))
    clock = pygame.time.Clock()
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
        screen.fill((20, 24, 40))
        pygame.display.flip()
        clock.tick(60)
        await asyncio.sleep(0)       # hand control back to the browser every frame

asyncio.run(main())

You can make the same code serve both desktop and web: the await asyncio.sleep(0) costs nothing on the desktop.

Step 4: test like a stranger

Before you share anything, test on a clean machine (a friend's computer or a fresh virtual machine) without Python installed:

Python A pre-release checklist you can run

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Fix the unchecked items before you upload. The no-sound-device case is easy to forget: wrap pygame.mixer.init() in try/except pygame.error so a missing audio device does not crash the game.

Step 5: share it

  • itch.io is the friendliest home for small games: upload a zip per platform, or a pygbag build zipped with index.html at its root and tick "This file will be played in the browser".
  • GitHub Releases suit open-source projects: attach the zips to a tagged release and write release notes.
  • Include a README with controls, a screenshot, system requirements and credits.
  • Licenses. Your own code can use MIT or any license you choose. Pygame uses the LGPL, so you may ship it in closed games, but keep the notices. Respect licenses of art and music (CC-BY needs credit), and include a CREDITS file.
  • Version and changelog. Show v0.3.1 on the title screen so bug reports mention it.
  • Feedback. Add a link to a form or Discord, and ask players for the one thing that confused them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do relative asset paths often fail in a one-file PyInstaller build?

    The working directory is not your project folder, so use a resource_path helper based on sys._MEIPASS.
  2. 2. Which PyInstaller flag hides the console window?

    --noconsole prevents the black terminal from appearing; --onefile only controls packaging into a single file.
  3. 3. What must a pygbag game do each frame?

    The browser needs control back every frame, and blocking calls would freeze the page.
  4. 4. On which system must the Windows .exe be built with PyInstaller?

    PyInstaller does not cross-compile; use each target system or a CI matrix.

Summary

  • Prepare first: asset paths with resource_path, requirements.txt, user-folder saves and crash logging.
  • PyInstaller (--noconsole --onefile --add-data --icon) builds an executable per operating system; keep a .spec file.
  • pygbag compiles to WebAssembly: use an async loop, OGG audio and no blocking calls.
  • Test on a clean computer, work through a release checklist and ship a README, licenses and a version number.
  • itch.io and GitHub Releases are the easiest places to publish.

Next: Snake Game