DEV Community

Cover image for Developing Retro Games with Python and Pyxel - Part 5: Final Project
Joelson Andrade
Joelson Andrade

Posted on AI-assisted

Developing Retro Games with Python and Pyxel - Part 5: Final Project

We have reached the final chapter of our series! In the previous four parts, you learned how the game loop works, drew shapes and sprites, captured player input, structured code with Object-Oriented Programming, and explored the Pyxel resource editor.

Now, we are going to put all these pieces together to build a complete arcade game from scratch: Meteor Shower. The goal is to pilot a ship at the bottom of the screen, dodge meteors falling from space, and survive as long as possible while the speed increases.

So that you can copy, paste, and play immediately without needing to create external files first, we will even generate the sound effects via code!

The 3 Missing Pillars for a Complete Game

Before jumping into the final code, we need to solve three mechanics present in practically any game:

1. State Management (Game Screens)

A game doesn't start straight into the action, and it doesn't freeze when the player loses. It switches between well-defined states:

  • START: displays the title and waits for the player to press ENTER or SPACE.
  • PLAYING: executes movement, spawns enemies, checks collisions, and adds points.
  • GAME_OVER: freezes the action, shows the final score, and allows restarting the match without closing the window.

Using a self.state variable inside update() and draw() organizes exactly what should be calculated and drawn at each moment.

2. Collision Detection (AABB)

How do we know if a meteor hit the ship? In 2D retro games, the fastest and most efficient method is AABB (Axis-Aligned Bounding Box).

We treat each object as a rectangle defined by position (x, y), width w, and height h. Two rectangles A and B are colliding when all four of these conditions are true at the same time:

def collided(ax, ay, aw, ah, bx, by, bw, bh):
    return (
        ax < bx + bw
        and ax + aw > bx
        and ay < by + bh
        and ay + ah > by
    )
Enter fullscreen mode Exit fullscreen mode

If there is horizontal and vertical overlap simultaneously, a hit has occurred.

3. Procedural Audio (pyxel.sounds)

In addition to loading .pyxres files created in the editor (as we saw in Part 4), Pyxel allows you to synthesize sound effects directly in Python using pyxel.sounds[n].set(). This is great for quick prototypes or single-file games.

Complete Code: Meteor Shower

Create a file named meteors.py, paste the code below, and run it with pyxel run meteors.py:

import random
import pyxel

# Game state constants
STATE_START = 0
STATE_PLAYING = 1
STATE_GAME_OVER = 2

class App:
    def __init__(self):
        pyxel.init(width=160, height=120, title="Meteor Shower")

        # Configure procedural sound effects (0 = explosion, 1 = point)
        pyxel.sounds[0].set("c2g1c1", "n", "742", "f", 15)
        pyxel.sounds[1].set("e3g3c4", "t", "464", "n", 8)

        # Create fixed stars for the space background
        self.stars = [
            (random.randint(0, 159), random.randint(0, 119), random.choice([5, 6, 7]))
            for _ in range(35)
        ]

        self.state = STATE_START
        self.high_score = 0
        self.reset_game()

        pyxel.run(self.update, self.draw)

    def reset_game(self):
        # Player data (ship)
        self.ship_w = 10
        self.ship_h = 8
        self.ship_x = (pyxel.width - self.ship_w) // 2
        self.ship_y = pyxel.height - 16
        self.ship_speed = 3

        # List of meteors: each item will be [x, y, size, speed]
        self.meteors = []
        self.score = 0

    def spawn_meteor(self):
        size = random.choice([6, 8, 10])
        x = random.randint(0, pyxel.width - size)
        # Speed gradually increases as the score goes up
        difficulty_bonus = min(2.5, self.score / 300)
        speed = random.uniform(1.2, 2.2) + difficulty_bonus
        self.meteors.append([x, -size, size, speed])

    def check_collision(self, ax, ay, aw, ah, bx, by, bw, bh):
        return ax < bx + bw and ax + aw > bx and ay < by + bh and ay + ah > by

    def update(self):
        if pyxel.btnp(pyxel.KEY_Q):
            pyxel.quit()

        if self.state == STATE_START:
            if pyxel.btnp(pyxel.KEY_RETURN) or pyxel.btnp(pyxel.KEY_SPACE):
                self.reset_game()
                self.state = STATE_PLAYING

        elif self.state == STATE_PLAYING:
            self.update_game()

        elif self.state == STATE_GAME_OVER:
            if pyxel.btnp(pyxel.KEY_R) or pyxel.btnp(pyxel.KEY_SPACE):
                self.reset_game()
                self.state = STATE_PLAYING

    def update_game(self):
        # 1. Ship movement
        if pyxel.btn(pyxel.KEY_LEFT) or pyxel.btn(pyxel.KEY_A):
            self.ship_x -= self.ship_speed
        if pyxel.btn(pyxel.KEY_RIGHT) or pyxel.btn(pyxel.KEY_D):
            self.ship_x += self.ship_speed

        self.ship_x = pyxel.clamp(x=self.ship_x, lower=0, upper=pyxel.width - self.ship_w)

        # 2. Periodic spawning of new meteors
        # Frequency increases as the score goes up
        interval = max(8, 22 - (self.score // 80))
        if pyxel.frame_count % interval == 0:
            self.spawn_meteor()

        # 3. Update meteors and check for collisions
        for meteor in self.meteors[:]:
            meteor[1] += meteor[3]  # Add speed on the Y axis

            # Check AABB collision between ship and meteor
            if self.check_collision(
                self.ship_x,
                self.ship_y,
                self.ship_w,
                self.ship_h,
                meteor[0],
                meteor[1],
                meteor[2],
                meteor[2],
            ):
                pyxel.play(ch=0, snd=0)
                self.high_score = max(self.high_score, self.score)
                self.state = STATE_GAME_OVER
                return

            # Remove meteors that went off the bottom of the screen
            if meteor[1] > pyxel.height:
                self.meteors.remove(meteor)

        # 4. Increment score for survival
        self.score += 1
        if self.score % 100 == 0:
            pyxel.play(ch=1, snd=1)

    def draw(self):
        pyxel.cls(pyxel.COLOR_BLACK)

        # Starry background (appears in all states)
        for sx, sy, scolor in self.stars:
            pyxel.pset(sx, sy, scolor)

        if self.state == STATE_START:
            pyxel.text(52, 42, "METEOR SHOWER", pyxel.COLOR_YELLOW)
            pyxel.text(32, 65, "ARROWS or A/D: Move", pyxel.COLOR_WHITE)
            pyxel.text(42, 82, "SPACE to Start", pyxel.COLOR_CYAN)

        elif self.state == STATE_PLAYING:
            self.draw_game()

        elif self.state == STATE_GAME_OVER:
            self.draw_game()
            # Central Game Over box
            pyxel.rect(30, 38, 100, 46, pyxel.COLOR_NAVY)
            pyxel.rectb(30, 38, 100, 46, pyxel.COLOR_RED)
            pyxel.text(62, 45, "GAME OVER", pyxel.COLOR_RED)
            pyxel.text(44, 58, f"SCORE: {self.score}", pyxel.COLOR_WHITE)
            pyxel.text(44, 66, f"BEST:  {self.high_score}", pyxel.COLOR_YELLOW)
            pyxel.text(40, 75, "SPACE: Play again", pyxel.COLOR_CYAN)

    def draw_game(self):
        # Draw the ship using a triangle + thruster
        tip_x = self.ship_x + (self.ship_w // 2)
        pyxel.tri(
            tip_x,
            self.ship_y,
            self.ship_x,
            self.ship_y + self.ship_h,
            self.ship_x + self.ship_w,
            self.ship_y + self.ship_h,
            pyxel.COLOR_CYAN,
        )
        # Blinking engine flame
        if pyxel.frame_count % 4 < 2:
            pyxel.rect(tip_x - 1, self.ship_y + self.ship_h, 3, 3, pyxel.COLOR_ORANGE)

        # Draw the meteors
        for mx, my, msize, _ in self.meteors:
            radius = msize // 2
            pyxel.circ(mx + radius, my + radius, radius, pyxel.COLOR_BROWN)
            pyxel.circb(mx + radius, my + radius, radius, pyxel.COLOR_ORANGE)

        # HUD (Scoreboard at the top)
        pyxel.text(4, 4, f"SCORE: {self.score}", pyxel.COLOR_WHITE)
        pyxel.text(104, 4, f"MAX: {self.high_score}", pyxel.COLOR_YELLOW)

if __name__ == "__main__":
    App()
Enter fullscreen mode Exit fullscreen mode

Notice an important detail in the line for meteor in self.meteors[:]:: the [:] slice creates a copy of the list during iteration. This prevents errors in Python when removing meteors that have left the screen while the loop is still running.

Final result:

Packaging and Distributing Your Game

Finished your game and want to send it to friends who don't have Python or Pyxel installed? Pyxel has native packaging tools that we briefly saw back in Part 1:

  1. Create a distributable package (.pyxapp): Bundles all your .py scripts and .pyxres files into a single compressed file:
pyxel package . meteors.py
Enter fullscreen mode Exit fullscreen mode

Anyone with Pyxel installed can run this file directly with pyxel play meteors.pyxapp.

  1. Generate a standalone executable (.exe / binary): Transforms the .pyxapp into a native executable that runs without needing to install Python:
pyxel app2exe meteors.pyxapp
Enter fullscreen mode Exit fullscreen mode
  1. Publish on the Web (HTML5 / WebAssembly): Generates an HTML page ready to host for free on itch.io or GitHub Pages, allowing anyone to play directly in the browser:
pyxel app2html meteors.pyxapp
Enter fullscreen mode Exit fullscreen mode

Ideas to Expand the Project

Now that the game is working, you can use everything you learned in the series to evolve it:

  • Replace shapes with sprites: open pyxel edit and replace the ship's triangle and the meteors' circles with pixel art using pyxel.blt().
  • Add shooting: create a self.bullets list that fires projectiles upward when the player presses Z or UP and destroys meteors in the way.
  • Bonus items: make golden stars fall occasionally to grant extra points or a temporary shield.

Series Wrap-up

Throughout these five articles, we went from the first empty window to a complete game with simple physics, collisions, audio, state management, and cross-platform export. The greatest charm of Pyxel is precisely proving that you don't need heavy engines to create fun experiences and learn real game engineering fundamentals.

To keep exploring, check out the official Pyxel documentation and run pyxel copy_examples to study the source code of platformers, puzzles, and shoot 'em ups made by the community. Happy coding and have fun creating!

Top comments (0)