Skip to main content

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.

ApproachWorks here?Notes
pygame, turtle window, OpenGLNoNeed a real screen / framebuffer
Pillow drawing PNGsPossible laterWould need extra packages and a page that shows images
ASCII grid + printYesSame 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​

Quiz

Frames and loops

1 / 2

Why 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.

CommandsResult
LL3
RRRRRRRRRR10

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​

Quiz

Hits

1 / 2

After this, what is aliens?

aliens = [2, 5, 8]
shot_col = 5
if 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.

InputOutput
5 then 2 5 8HIT
1 then 2 5 8MISS

Exercises​

Activity: Draw the board

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:

  1. Keep ASCII and add colors with ANSI codes in a real terminal (not required here).
  2. Bake Pillow into the Piston Python image (pip install pillow at package build time) and print a base64 PNG β€” then a small site component could display it.
  3. 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).