🚀 Mini Projects, lesson 4 of 6
Project: tic-tac-toe
Model a game board with nested lists: draw it, validate moves, find the winner.
12 min
3 exercises
1 quiz
0/4 solved
Getting Python ready… examples can run in a moment.
Board games are great practice for nested lists. A
tic-tac-toe board is 3 rows of 3 cells, each "X",
"O" or " " (empty), and board[row][col] reads
one cell.
- Board: create it and draw it as text
- Moves: place a mark, rejecting bad moves
- Winner: check rows, columns and diagonals
Seeing the trap
One move on the bad board shows up in every row!
print(bad[0] is bad[1]) confirms they're the same
list.
Three references to one row
[" "] * 3 builds one row. * 3 on the outer list then copies the reference to that row three times: bad holds the same row three times.
What does this print?
Step 1: create and draw the board
new_board()returns 3 separate rows of 3" "cellsrender(board)returns the board as text: cells joined by|, rows separated by a-+-+-line
X|O|
-+-+-
|X|
-+-+-
| |O
Step 2: make a move
Write make_move(board, row, col, player):
- raise
ValueErrorifroworcolisn't 0, 1 or 2 - raise
ValueErrorif the square is already taken - otherwise put
playerin that square
Checking the 8 lines, in order
Row 0: X, O, X. Two different marks, so set(line) has 2 items: no win.
3 rows, then 3 columns, then 2 diagonals. A line wins when its first cell isn't empty and all three cells are equal.
Step 3: find the winner
winner(board)returns"X"or"O"if that player has three in a row (any row, column or diagonal), otherwiseNoneis_full(board)returnsTruewhen no square is empty
Tip: collect all 8 lines (3 rows, 3 columns, 2 diagonals) in one list, then check each.
Play a whole game
All three steps working together. Change the moves so the game ends in a draw, or play onto a taken square to see your ValueError.