🚀 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
Example
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.
Quiz
What does this print?
O
.
IndexError
None
Exercise
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
Exercise
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
Exercise
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.
Example
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.