You make a Space Invaders game in Python by installing Pygame, setting up a fixed-size window and game loop, representing the player, invaders, and bullets as rectangles, handling input and collision each frame, and adding rules for waves, score, and game over. The core runnable game fits in about 150–250 lines. The one condition that matters most: you need to understand classes and basic coordinate geometry, because the invaders' grid movement and bullet collisions are built on both.
This guide walks through a complete, playable version. It doesn't just hand you a sketch — it explains why each part works, what breaks in practice, and how to extend the game once the basics run.
What you need before writing any code
Pygame is the standard choice for a first 2D game in Python because it's a thin layer over SDL2: you get a window, an event queue, and surface blitting without a heavy engine. Alternatives exist (Arcade, pygame-ce, Tkinter canvas), but Pygame's documentation and community examples are the deepest, so it's the right starting point.
Prerequisites:
Python 3.9 or newer. Any recent stable release works; Pygame publishes wheels for current CPython versions on Windows, macOS, and Linux. Comfort with functions, while loops, lists, and classes with init and methods. A code editor with a run button, and a terminal to install packages.
Install the library:
If you're on a system-managed Python (some Linux distros), install into a virtual environment instead:
Check success: run python -c "import pygame; print(pygame.version.ver)". A version number means you're ready. A ModuleNotFoundError means the install went to a different interpreter than the one running your script — the most common setup failure, fixed by using the same python/pip pair or a virtual environment.
One version caveat: Pygame's classic 2.x line and the community fork pygame-ce import under the same import pygame name, and both work for this project. Don't install both into one environment; pick one.
The skeleton: window, loop, and frame clock
Every Pygame game shares one structure: initialize, create a display, then loop forever doing three things — read events, update state, draw. The clock caps the frame rate so the game runs at the same speed on fast and slow machines.
Run this and you get a dark blue window that closes cleanly. clock.tick(60) waits as needed so the loop runs at roughly 60 frames per second. If you omit it, the loop spins as fast as the CPU allows, the game speed varies by machine, and a laptop fan spins up for no reason.
Notice the event loop handles pygame.QUIT — the window's close button. Skipping that is the classic beginner bug where the window freezes and the OS reports the app as unresponsive.
Modeling the player and invader grid
Space Invaders is fundamentally a rectangle game. The original 1978 arcade cabinet drew pixel sprites, but collision detection ran on bounding boxes, and that's still the pragmatic approach. Pygame's Rect gives you position, size, and built-in collision tests in one object.
The player is a ship constrained to the bottom of the screen and to horizontal movement:
The clamping checks (rect.left > 0, rect.right < WIDTH) stop the ship at the screen edges. Without them the ship slides off and you can't shoot properly. The cooldown counter, decremented once per frame, throttles firing — without it, holding the space bar spawns a bullet every frame and the screen fills instantly.
The invaders are stored as a list of Rects arranged in rows and columns:
Build the fleet with nested loops:
That's 55 invaders, 40×30 pixels each, spaced 60 horizontally and 50 vertically. The arithmetic matters: 11 columns at 60 pixels starting at x=60 occupy 60 + 10×60 + 40 = 700 pixels, comfortably inside an 800-pixel window with margin for the fleet to step sideways.
Why a grid rather than individually positioned enemies? Because classic Space Invaders moves the whole fleet as a unit — all invaders advance together, then step down when any reaches an edge. A list of independent objects with a shared movement routine reproduces that exactly.
Fleet movement: the sideways march and the edge drop
The fleet's movement is the mechanic that makes Space Invaders feel like Space Invaders. Each frame (or every few frames), every living invader shifts horizontally by a fixed step in the current direction. When the outermost living invader would cross a screen edge, the whole fleet reverses direction and drops down.
Track three variables: direction (1 or -1), a horizontal step, a vertical drop, and a timer so the march isn't a blur.
Why recompute edges only among living invaders: after you shoot the leftmost column, the fleet shouldn't keep marching left until the dead sprites' old positions clear the wall. Computing min/max over living invaders only makes the fleet hug the new edge immediately, which is how the arcade original behaves.
Tuning feel: MOVE_INTERVAL controls the march tempo. At 60 FPS, 30 frames is a step every half second — deliberate and easy. Dropping it to 10 makes the fleet frantic. A common enhancement is to shorten the interval as invaders die, so the last few survivors move faster and the tension ramps up, mirroring the original's speed-up.
A failure to watch for: if the fleet drops far enough that any invader's bottom passes the player's top, the game should end. A fleet that reaches the bottom while you're still "playing" is a bug, not a feature.
Bullets, input, and collision
Bullets are the simplest objects in the game: a small Rect that moves vertically each frame and is removed when it leaves the screen or hits something. Keep two lists — player bullets going up, invader bullets going down.
Firing goes in the player's update, gated by cooldown:
A vy of -10 means 10 pixels up per frame, about 600 pixels per second at 60 FPS. At that speed a bullet crosses the 540-pixel playfield in under a second — fast enough to feel responsive, slow enough that you can track it.
Collision is a nested loop, which is fine at this scale:
Two details carry weight here. Iterating over player_bullets[:] (a copy) while you might remove bullets prevents skipping elements. And the break after a hit stops one bullet from destroying two invaders stacked in the same spot — impossible with a clean grid, but cheap insurance if you later add overlapping formations.
Invader return fire: each frame, give a small probability that a random living invader fires a bullet downward:
At 60 FPS, 0.02 per frame is roughly 1.2 shots per second across the fleet — about a 30–40 shot storm during a full wave. That's playable but genuinely dangerous. Tune it down (0.01) if your first playtest feels unfair.
Player hit: check every invader bullet against the player's rect. On a hit, either end the game or deduct from a lives counter.
A colliderect test is a bounding-box overlap check, not pixel-perfect. At these sizes the difference is a few pixels of unfairness at the corners, which no player will notice. Pixel-masking (pygame.mask) exists if you later switch to sprites with irregular shapes, but for rectangles it's wasted effort.
Putting the loop together
Now assemble the full game loop with a state variable for game over. Here's the complete structure, with the pieces from above wired in:
Restart is optional but cheap: on K_r when game_over is true, reset the player's rect, rebuild the invaders with your original nested loops, clear both bullet lists, and zero the score. Don't re-call pygame.init(); that's a setup call, not a reset.
A subtle trap: player.shoot() reads the global player_bullets list. Functions defined at module level work only if the list is defined globally, and mutations like .append are fine without a global statement — only rebinding (like player_bullets = [...]) needs it. Note that the cleanup line player_bullets = [b for ...] does rebind, which is easy to miss in a function.
Structuring the game in a class with attributes avoids this whole category of confusion once the code grows past a couple hundred lines.
Adding waves, lives, and a difficulty curve
A one-wave game ends after a single screen of invaders, which takes maybe 40 seconds. Three additions make it feel like a real game — and they're where most of the design thinking lives.
Waves. When no living invaders remain, rebuild the fleet, increase the fleet speed, and keep the score. The cleanest way is a start_wave(n) function that sets MOVE_INTERVAL = max(6, 30 - (wave - 1) * 4). Wave 1 steps every 30 frames, wave 2 every 26, and so on, bottoming out at 6 frames. The floor matters: below roughly 6 frames per step, the fleet teleports across the screen and the game becomes an unpredictable reflex test rather than a shooting game.
Lives. A hit doesn't end the run immediately. Give the player three lives; on a hit, clear invader bullets, reset the player's x to center, and grant about half a second of invulnerability (30 frames counted down in player.update). Without the invulnerability window, a bullet storm can hit you twice within a few frames, burning two lives for one mistake.
Score and high score. Ten points per invader is fine. Keep the high score in memory only; persisting it to a file is a two-line job but introduces error handling for a corrupt or missing file, so leave it for a later session unless you want the file I/O practice.
A difficulty wrinkle worth knowing: the arcade original made the last invader move remarkably fast, dropping the step interval as the fleet thinned. You can emulate this by scaling MOVE_INTERVAL by the fraction of invaders remaining:
This makes the final stragglers genuinely dangerous and gives the end of each wave its own rhythm. It's the single change that most makes a homemade clone feel like the real thing.
Drawing, sound, and polish within reason
Rectangles work, but the game reads better with a few cheap upgrades.
Sprites. Pygame's image.load() accepts PNGs; pair each invader Rect with a loaded image and blit it at the rect's position. The original game used two-frame animation per invader — swap between two images on a timer and the fleet looks alive. If you don't want to draw sprites, a simple triangle-free approach is to vary rect colors by row, which at least makes rows distinguishable.
Sound. pygame.mixer plays WAV or OGG files. The classic four-note descending march (the famous "boots" sound) plays one note per fleet step, which doubles as an audio cue for movement tempo. pygame.mixer.Sound("shoot.wav").play() is the whole API for effects. Guard pygame.mixer.init() in a try block, because it fails on machines with no audio device, and a silent game is better than a crash.
What to skip. Particle systems, scrolling starfields, and screen-shake are fun but multiply the code without changing how the game plays. Get the core loop, waves, and lives working first. Then add exactly one polish item, playtest, and repeat.
The most underrated polish item: a start screen and a brief pause after each wave. New players need a second to register that they've cleared the fleet before the next one drops, and a moment to prepare before wave one. A 60-frame delay with a "WAVE 2" text blit costs five lines and transforms the pacing.
Common bugs and how to diagnose them
These failures show up in almost every first attempt. Each has a symptom and a likely cause.
The window freezes on launch. You forgot to drain the event queue, specifically pygame.event.get() handling pygame.QUIT. The OS assumes a hung app.
Bullets spawn in a solid column. You're firing every frame while the space bar is held. Add the cooldown counter; don't rely on KEYDOWN alone, because key repeat behavior varies by OS.
The game runs at different speeds on different machines. You're missing clock.tick(60), or you wrote movement in pixels per frame and later replaced the frame rate. Keep the frame rate fixed and express speeds in pixels per frame; at a fixed 60 FPS that's a clean, reproducible unit.
The fleet never reverses. Your edge check tests the old position after moving, or computes min/max over all invaders including dead ones. Recompute from living invaders only and test the next position against the wall, as the code above does.
Invaders vanish two at a time. One bullet is scoring twice. Add the break after a hit and mark the bullet off-screen before the cleanup pass.
The score keeps incrementing after game over. You set game_over = True but didn't gate the update block. Wrap all game logic in if not game_over:.
Collisions feel unfair near sprite edges. You're testing the wrong rects — usually the image rect versus the logical rect. Keep one Rect per object as the source of truth and use it for both drawing and collision.
The right approach to all of these is a three-line debug habit: print the counts (len(player_bullets), sum(inv.alive for inv in invaders)) and the fleet's current left/right edges each second, not each frame. A flood of prints hides the transition you're looking for.
Design decisions and limits worth knowing
A few choices shape the game more than they seem to.
Frame-rate dependence versus delta time. This build is frame-rate dependent: all speeds are pixels per frame at a fixed 60 FPS. That's simpler and perfectly fine for a single-screen game. If you later allow variable frame rates (e.g., 120 Hz monitors), you'll need delta-time scaling — multiply every movement by dt — which touches every update method. For a first game, a fixed tick is the right trade.
The collision cost grows as a product. Player bullets times invaders is a nested loop of at most a handful by 55, trivial. If you scale to hundreds of enemies and dozens of bullets, use spatial bucketing or a quadtree — but at this size, optimizing is premature. The actual limit of this architecture is the ship count, not the frame rate.
Bounding boxes versus masks. Rectangles misjudge diagonal grazes by a few pixels, which nobody notices. Switching to pixel masks costs CPU and complexity; only worthwhile with irregular sprites and a game that depends on precise hits.
The bottom of the playfield is a design lever. Whether invaders can reach the player, whether they end the game at a line, or whether the fleet drops infinitely all change the tension. The arcade original ends when the fleet reaches the bottom, and keeping that rule plus a visible danger line makes the player's position decisions meaningful. A game where the fleet can't threaten you is a shooting gallery, not Space Invaders.
Persistence is deceptively simple. Saving a high score to a text file is easy; handling a missing file, a read-only directory, or a corrupted value adds branches that distract from the game. If you want the file I/O practice, write a small load_high_score() that returns 0 on any exception and move on.
A realistic scope check. A complete version of everything described here — skeleton, player, grid, fleet movement, bullets, collisions, waves, lives, score, and basic sound — is roughly 200–250 lines. That's two to four focused sessions for someone comfortable with the prerequisites. The temptation to add features before the core loop plays well is the main risk to finishing. Build the 150-line version, play it, and let its weaknesses tell you what to add next.
The single best habit for this project is to get a running game as early as possible and keep it running. Add the fleet movement, hit the run button, watch invaders march into the wall and fix it, then add bullets. Each addition should leave a playable game behind it, because the bugs are far easier to find when the game still runs and you can see exactly which behavior changed.