Chapter 10a - Space Invaders
You will build a text Space Invaders: a 2D grid printed each turn. That is the version that runs in this siteβs Python sandbox.
Why not pygame?β
Piston runs Python without a window. There is no display, mouse, or speaker.
| Approach | Works here? | Notes |
|---|---|---|
pygame, turtle window, OpenGL | No | Need a real screen / framebuffer |
| Pillow drawing PNGs | Possible later | Would need extra packages and a page that shows images |
ASCII grid + print | Yes | Same idea as arcade: a 2D board, a player, aliens, a game loop |
So the βrendering libraryβ is a handful of functions that fill a list-of-lists and print it. You already have lists and functions from chapters 8 and 9.
A tiny draw libraryβ
A cell is one character. A frame is a rectangle of cells.
EMPTY = "."
PLAYER = "A"
ALIEN = "M"
SHOT = "|"
def make_board(rows, cols):
return [[EMPTY] * cols for _ in range(rows)]
def put(board, row, col, ch):
if 0 <= row < len(board) and 0 <= col < len(board[0]):
board[row][col] = ch
def draw(board):
for row in board:
print("".join(row))
π§ͺ Draw one frame
Mini quiz β frames and loopsβ
Frames and loops
1 / 2Why can pygame not open a window in this sandbox?
Pick an answer to see if you are right.
Game loop (one command per frame)β
Each line of input is a command: L move left, R move right, S shoot (we will grade movement first).
.....M.....
...........
...........
.....A.....
Player starts at the bottom, middle.
Challenge: move the playerβ
Given width 11, player column starts at 5. Read a line of commands made of L and R. Print the final column (0β10). Ignore moves that would leave the board.
| Commands | Result |
|---|---|
LL | 3 |
RRRRRRRRRR | 10 |
Aliens as a list of columnsβ
Store alien columns in a list, e.g. [2, 5, 8]. A hit removes that column from the list.
π§ͺ Hit detection idea
Mini quiz β hitsβ
Hits
1 / 2After this, what is aliens?
aliens = [2, 5, 8]shot_col = 5if shot_col in aliens:aliens.remove(shot_col)
Pick an answer to see if you are right.
Challenge: did the shot hit?β
Read shot_col then a line of alien columns. Print HIT if the shot column is in that list, otherwise MISS.
| Input | Output |
|---|---|
5 then 2 5 8 | HIT |
1 then 2 5 8 | MISS |
Exercisesβ
Write draw_line(width, player_col) so it returns a string of length width: . everywhere except A at player_col.
Expected for 11 5:
.....A.....
Going further (optional)β
If you later want pixels, options are:
- Keep ASCII and add colors with ANSI codes in a real terminal (not required here).
- Bake Pillow into the Piston Python image (
pip install pillowat package build time) and print a base64 PNG β then a small site component could display it. - Browser game in JavaScript/canvas, with Python only scoring logic.
For class, stay on the grid: it is the same architecture as the arcade game (state, input, collide, redraw).