liveBook · Manning

Tic-tac-toe board

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

A Tic-Tac-Toe board is a game grid containing nine cells, each marked with X, O, or an empty marker.

A Tic-Tac-Toe board is a 3-by-3 grid of nine cells. Each cell contains X, O, or a period marking it as empty. The board makes the game’s changing state explicit: it records occupied cells before and after a move. section 21.0 section 21.4

A compact string representation supports display, validation, and updates:

  • Store exactly nine characters in positions corresponding to cells 1 through 9; use . for an open cell. section 21.1
  • Render a mark when a cell contains X or O; otherwise render the cell number so a player can choose it. section 21.1
  • Translate a displayed cell number to a string index with cell - 1. section 21.1.2 section 21.2.1
  • Convert the string to a list when changing one character, because strings are immutable. section 21.1.2 section 21.4
  • Validate the board with a nine-character pattern containing only ., X, and O, then reject moves into occupied cells. section 21.2.1

Representing and displaying a board

The string X.O..O..X places X in cells 1 and 9, O in cells 3 and 6, and leaves the remaining cells open. A rendered board shows those marks while displaying 2, 4, 5, 7, and 8 as available cell choices. The board XXXOO.... reports that X has won. section 21.1

$ ./tictactoe.py -b X.O..O..X
-------------
| X | 2 | O |
-------------
| 4 | 5 | O |
-------------
| 7 | 8 | X |
-------------
No winner.

Inspect a concrete rendering of a partially occupied board and compare its nine-character encoding with visible cell positions. section 21.1

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains string encoding, rendering, validation, indexing, and mutation, while deferring complete interactive-game state.
Examples
Uses empty, partially occupied, updated, and winning boards such as ........., X.O..O..X, and XXXOO.... .
What you can do after
Build it from scratch as a validated command-line board that accepts a move, renders cells, and reports a winner.
How it connects
Connects board representation with program state, strings, lists, regular expressions, Boolean aggregation, and zero-based indexing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.