Skip to content
Python project #15Intermediate

Tic-Tac-Toe with Minimax

Play two-player tic-tac-toe or challenge an unbeatable computer that uses the minimax algorithm with memoisation.

Estimated time
~3 hours to build
Files
4 files · 337 lines
Technologies
Python 3, functools.lru_cache, Recursion

Introduction

Tic-tac-toe is small enough to search completely, which makes it the perfect introduction to game-tree search. The computer player tries every possible future and never loses.

Problem statement

Show a 3×3 board and let players choose cells 1–9. Reject non-numbers, out-of-range cells and taken cells. Detect wins and draws. In computer mode, O plays perfectly using minimax. Keep a score across games until the player quits.

Objectives

  • Represent a board compactly as a string
  • Detect wins with a table of lines
  • Implement recursive minimax
  • Speed up recursion with functools.lru_cache

Features

  • Two-player and versus-computer modes
  • Input validation for cells
  • Win and draw detection
  • Unbeatable minimax opponent
  • Score across games

Concepts demonstrated

  • Game-tree search
  • Minimax
  • Memoisation
  • Immutable state as strings

System architecture

The board is a 9-character string, which is immutable and hashable, so minimax can be cached with lru_cache. winner checks the eight lines in LINES. minimax returns the best (score, move) for the player to move: +1 if O can force a win, −1 if X can, 0 for a draw. play runs one game and main handles the menu and score.

Folder structure

TextProject tree
tic-tac-toe/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

101 lines
Pythonmain.py
"""Tic-Tac-Toe for two players or against an unbeatable computer (minimax).
Cells are numbered like a phone keypad's first three rows:
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
"""
import sys
from functools import lru_cache
LINES = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]
def ask(prompt: str) -> str | None:
try:
line = input(prompt)
except EOFError:
print()
return None
if not sys.stdin.isatty():
print(line)
return line.strip().lower()
def winner(board: str) -> str | None:
for a, b, c in LINES:
if board[a] != " " and board[a] == board[b] == board[c]:
return board[a]
return "draw" if " " not in board else None
@lru_cache(maxsize=None)
def minimax(board: str, player: str) -> tuple[int, int]:
"""Best (score, move) for player: +1 means O (the computer) wins, -1 means X wins."""
result = winner(board)
if result == "O":
return 1, -1
if result == "X":
return -1, -1
if result == "draw":
return 0, -1
best: tuple[int, int] | None = None
for i in range(9):
if board[i] == " ":
score, _ = minimax(board[:i] + player + board[i + 1:], "X" if player == "O" else "O")
if best is None or (player == "O" and score > best[0]) or (player == "X" and score < best[0]):
best = (score, i)
return best
def show(board: str) -> None:
rows = [" | ".join(board[r * 3:r * 3 + 3]) for r in range(3)]
print("\n---------\n".join(f" {row}" for row in rows))
def play(vs_computer: bool) -> str | None:
board, player = " " * 9, "X"
while winner(board) is None:
show(board)
if vs_computer and player == "O":
_, move = minimax(board, "O")
print(f"Computer plays {move + 1}")
else:
answer = ask(f"Player {player}, choose a cell (1-9): ")
if answer is None:
return None
if not answer.isdigit() or not 1 <= int(answer) <= 9:
print("Please type a number from 1 to 9.")
continue
move = int(answer) - 1
if board[move] != " ":
print("That cell is taken.")
continue
board = board[:move] + player + board[move + 1:]
player = "O" if player == "X" else "X"
show(board)
result = winner(board)
print("It's a draw!" if result == "draw" else f"{result} wins!")
return result
def main() -> None:
score = {"X": 0, "O": 0, "draw": 0}
while True:
choice = ask("\n1) Two players 2) Play against the computer q) Quit: ")
if choice is None or choice == "q":
break
if choice not in ("1", "2"):
print("Choose 1, 2 or q.")
continue
result = play(vs_computer=choice == "2")
if result is None:
break
score[result] += 1
print(f"Score - X: {score['X']} O: {score['O']} draws: {score['draw']}")
print("Thanks for playing!")
if __name__ == "__main__":
main()

What each file does

main.py
Board helpers, the cached minimax search, the game loop and the menu.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
1) Two players 2) Play against the computer q) Quit: 3
Choose 1, 2 or q.
1) Two players 2) Play against the computer q) Quit: 1
| |
---------
| |
---------
| |
Player X, choose a cell (1-9): 1
X | |
---------
| |
---------
| |
Player O, choose a cell (1-9): 5
X | |
---------
| O |
---------
| |
Player X, choose a cell (1-9): 2
X | X |
---------
| O |
---------
| |
Player O, choose a cell (1-9): 4
X | X |
---------
O | O |
---------
| |
Player X, choose a cell (1-9): 3
X | X | X
---------
O | O |
---------
| |
X wins!
Score - X: 1 O: 0 draws: 0
1) Two players 2) Play against the computer q) Quit: 2
| |
---------
| |
---------
| |
Player X, choose a cell (1-9): 5
| |
---------
| X |
---------
| |
Computer plays 1
O | |
---------
| X |
---------
| |
Player X, choose a cell (1-9): 1
That cell is taken.
O | |
---------
| X |
---------
| |
Player X, choose a cell (1-9): 9
O | |
---------
| X |
---------
| | X
Computer plays 3
O | | O
---------
| X |
---------
| | X
Player X, choose a cell (1-9): 2
O | X | O
---------
| X |
---------
| | X
Computer plays 8
O | X | O
---------
| X |
---------
| O | X
Player X, choose a cell (1-9): 4
O | X | O
---------
X | X |
---------
| O | X
Computer plays 6
O | X | O
---------
X | X | O
---------
| O | X
Player X, choose a cell (1-9): 7
O | X | O
---------
X | X | O
---------
X | O | X
It's a draw!
Score - X: 1 O: 0 draws: 1
1) Two players 2) Play against the computer q) Quit: q
Thanks for playing!
Input
3
1
1
5
2
4
3
2
5
1
9
2
4
7
q

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/expected-output.txt.
  • Menu choice 3 is rejected; in the two-player game X wins with cells 1, 2 and 3 after a taken-cell error.
  • Against the computer, X opens in the centre, the computer answers in a corner and blocks every threat.
  • The second game ends in a draw and the final score is X 1, O 0, draws 1.

Common errors

The computer is very slow

Cache minimax results (the board is a string, so lru_cache works) to avoid re-searching positions.

Moves overwrite taken cells

Check board[move] before placing a mark.

Possible improvements

  • Add an easy mode that sometimes plays randomly
  • Let the computer play X as well
  • Generalise to 4×4 with depth-limited search

Additional challenges

  1. 1Count how many positions minimax evaluates with and without the cache.
  2. 2Add alpha-beta pruning.
  3. 3Show the computer's evaluation of every free cell.

Built and tested it yourself? Mark it to update your dashboard.