Project: tic-tac-toe

Mini Projects, lesson 4 of 6

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

  1. Board: create it and draw it as text
  2. Moves: place a mark, rejecting bad moves
  3. 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.

Walkthrough

Three references to one row

badlist012list' '0' '1' '2
Step 1 of 3

[" "] * 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.

the shared row
one change, seen in every row
only row 0 changed
Quiz

What does this print?

Exercise

Step 1: create and draw the board

  • new_board() returns 3 separate rows of 3 " " cells
  • render(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 ValueError if row or col isn't 0, 1 or 2
  • raise ValueError if the square is already taken
  • otherwise put player in that square
Walkthrough

Checking the 8 lines, in order

012012XOXOXO X
Step 1 of 7
line = ['X', 'O', 'X']

Row 0: X, O, X. Two different marks, so set(line) has 2 items: no win.

line being checked
three in a row

3 rows, then 3 columns, then 2 diagonals. A line wins when its first cell isn't empty and all three cells are equal.

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), otherwise None
  • is_full(board) returns True when 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.