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.

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