Tic-tac-toe

Play a friend or a computer opponent that never loses. A gentle introduction to game AI with the minimax algorithm.

Beginner2 min readUpdated
Tic-tac-toe screenshot: a board with two X and two O marks and the score tally below
Screenshot captured from the Python source below running in pygame-ce.
Difficulty
Beginner
Source size
189 lines, 1 file
Requires
Python 3.10+, pygame-ce or pygame
Assets
None (drawn in code)

Controls

  • Mouse click Place a mark
  • Arrow keys + Space Enter Move and place
  • M Switch between 1 and 2 players
  • R New round
On this page

What you'll learn#

  • Representing a board as a string
  • Checking all winning lines
  • The minimax algorithm for perfect play
  • Caching results with functools.lru_cache
  • Adding a short delay before the computer moves

Run it on your computer#

  1. Install Python 3.10 or newer and Pygame: python -m pip install pygame-ce (or pygame). See the installation guides.
  2. Download tic_tac_toe.py into any folder.
  3. Open a terminal in that folder and run python tic_tac_toe.py.

No images or sounds are needed: everything is drawn in code. The game also runs unchanged in Pygame Online, because its loop uses asyncio to hand control to the browser each frame.

How it works#

The board#

The board is a nine-character string such as "XO X O ", indexed 0 to 8 from the top-left. Strings are immutable and hashable, which matters for caching. winner() checks the eight possible lines and reports a win, a draw or nothing yet.

Minimax#

To choose a move, the computer imagines every possible continuation of the game. X tries to maximise the score (+1 for an X win), O tries to minimise it (-1 for an O win), and a draw scores 0. Each player assumes the other plays perfectly. Because tic-tac-toe is small, the search can reach the end of every game, so the computer never loses. The project's tests play every possible sequence of human moves against it and confirm this.

Caching#

@lru_cache remembers the result for each board and player, so positions reached by different move orders are only analysed once. The first move takes a fraction of a second; later ones are instant.

Complete source code#

tic_tac_toe.pyDownloadRun online
"""Tic-tac-toe - a Pygame.net game project.

Play against a friend or against a computer that uses the minimax
algorithm (it never loses). Press M to switch modes.

Run it:   pip install pygame-ce     (or: pip install pygame)
          python tic_tac_toe.py
Controls: Click a square, or use the arrow keys and Space/Enter.
          M switches between 1 and 2 players, R starts a new round.
License:  MIT - https://pygame.net/licenses/
"""
import asyncio
from functools import lru_cache

import pygame

WIDTH, HEIGHT = 640, 480
FPS = 60
SIZE = 110
LEFT = (WIDTH - SIZE * 3) // 2
TOP = 66

BG = (16, 26, 48)
GRID = (91, 147, 230)
X_COLOR = (244, 197, 49)
O_COLOR = (157, 194, 255)
WHITE = (230, 236, 247)
WIN_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 winner(board):
    for a, b, c in WIN_LINES:
        if board[a] != " " and board[a] == board[b] == board[c]:
            return board[a], (a, b, c)
    if " " not in board:
        return "draw", None
    return None, None


@lru_cache(maxsize=None)
def minimax(board, player):
    """Return (score, move) for `player` to move. Scores: X win +1, O win -1, draw 0."""
    result, _ = winner(board)
    if result == "X":
        return 1, None
    if result == "O":
        return -1, None
    if result == "draw":
        return 0, None
    best = None
    for i, cell in enumerate(board):
        if cell != " ":
            continue
        child = board[:i] + player + board[i + 1:]
        score, _ = minimax(child, "O" if player == "X" else "X")
        if best is None or (player == "X" and score > best[0]) or (player == "O" and score < best[0]):
            best = (score, i)
    return best


class Game:
    def __init__(self):
        self.font = pygame.font.Font(None, 34)
        self.big = pygame.font.Font(None, 52)
        self.vs_computer = True
        self.tally = {"X": 0, "O": 0, "draw": 0}
        self.new_round()

    def new_round(self):
        self.board = " " * 9
        self.turn = "X"            # the human is always X against the computer
        self.result = None
        self.line = None
        self.cursor = 4
        self.think = 0.0

    def play(self, index):
        if self.result or self.board[index] != " ":
            return False
        self.board = self.board[:index] + self.turn + self.board[index + 1:]
        self.result, self.line = winner(self.board)
        if self.result:
            self.tally[self.result] += 1
        else:
            self.turn = "O" if self.turn == "X" else "X"
            if self.vs_computer and self.turn == "O":
                self.think = 0.35     # short pause so the reply is visible
        return True

    def handle_event(self, event):
        human_turn = not (self.vs_computer and self.turn == "O")
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            if self.result:
                self.new_round()
                return
            x, y = event.pos
            c, r = (x - LEFT) // SIZE, (y - TOP) // SIZE
            if 0 <= c < 3 and 0 <= r < 3 and human_turn:
                self.cursor = r * 3 + c
                self.play(self.cursor)
        elif event.type == pygame.KEYDOWN:
            c, r = self.cursor % 3, self.cursor // 3
            if event.key == pygame.K_LEFT:
                c = (c - 1) % 3
            elif event.key == pygame.K_RIGHT:
                c = (c + 1) % 3
            elif event.key == pygame.K_UP:
                r = (r - 1) % 3
            elif event.key == pygame.K_DOWN:
                r = (r + 1) % 3
            elif event.key in (pygame.K_SPACE, pygame.K_RETURN):
                if self.result:
                    self.new_round()
                elif human_turn:
                    self.play(self.cursor)
                return
            elif event.key == pygame.K_r:
                self.new_round()
                return
            elif event.key == pygame.K_m:
                self.vs_computer = not self.vs_computer
                self.tally = {"X": 0, "O": 0, "draw": 0}
                self.new_round()
                return
            self.cursor = r * 3 + c

    def update(self, dt):
        if self.vs_computer and self.turn == "O" and not self.result:
            self.think -= dt
            if self.think <= 0:
                _, move = minimax(self.board, "O")
                self.play(move)

    def cell_rect(self, i):
        return pygame.Rect(LEFT + (i % 3) * SIZE, TOP + (i // 3) * SIZE, SIZE, SIZE)

    def draw(self, surface):
        surface.fill(BG)
        mode = "You (X) vs computer (O)" if self.vs_computer else "Two players"
        surface.blit(self.font.render(mode + "   -   M to switch", True, WHITE), (LEFT - 60, 28))
        for i in range(1, 3):
            pygame.draw.line(surface, GRID, (LEFT + i * SIZE, TOP), (LEFT + i * SIZE, TOP + 3 * SIZE), 4)
            pygame.draw.line(surface, GRID, (LEFT, TOP + i * SIZE), (LEFT + 3 * SIZE, TOP + i * SIZE), 4)
        for i, mark in enumerate(self.board):
            r = self.cell_rect(i).inflate(-36, -36)
            if mark == "X":
                pygame.draw.line(surface, X_COLOR, r.topleft, r.bottomright, 10)
                pygame.draw.line(surface, X_COLOR, r.topright, r.bottomleft, 10)
            elif mark == "O":
                pygame.draw.circle(surface, O_COLOR, r.center, r.width // 2, 9)
        if not self.result:
            pygame.draw.rect(surface, WHITE, self.cell_rect(self.cursor).inflate(-8, -8), 2, border_radius=6)
        if self.line:
            a, c = self.cell_rect(self.line[0]).center, self.cell_rect(self.line[2]).center
            pygame.draw.line(surface, (232, 93, 82), a, c, 8)
        y = TOP + 3 * SIZE + 12
        if self.result:
            msg = "It's a draw" if self.result == "draw" else f"{self.result} wins!"
            t = self.big.render(msg + "  (Space)", True, X_COLOR)
        else:
            t = self.font.render(f"{self.turn} to play", True, WHITE)
        surface.blit(t, t.get_rect(midtop=(WIDTH // 2, y)))
        tally = self.font.render(f"X {self.tally['X']}   O {self.tally['O']}   Draws {self.tally['draw']}", True, WHITE)
        surface.blit(tally, tally.get_rect(midbottom=(WIDTH // 2, HEIGHT - 6)))


async def main():
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("Tic-tac-toe - Pygame.net")
    clock = pygame.time.Clock()
    game = Game()
    running = True
    while running:
        dt = clock.tick(FPS) / 1000
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            else:
                game.handle_event(event)
        game.update(dt)
        game.draw(screen)
        pygame.display.flip()
        await asyncio.sleep(0)
    pygame.quit()


if __name__ == "__main__":
    asyncio.run(main())

The code is released under the MIT license: use it, change it and build on it. See licenses.

Ideas to extend it#

  1. Add difficulty levels: the computer picks a random move some of the time.
  2. Let the computer play X and the human play O.
  3. Highlight the winning line with an animation.
  4. Extend the board to 4 × 4 and add depth-limited minimax.
  5. Show a running win/draw/loss tally saved between sessions.
↑ ↓ to moveEnter to openEsc to close