Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 41 ยท Projects and Practice

Project: Tic Tac Toe with Pygame and an Unbeatable AI

Build a mouse-driven Tic Tac Toe in Pygame: board logic, click-to-cell mapping, win detection, a minimax AI that never loses, game-over screen and restart.

Tic Tac Toe is small enough to finish in an afternoon and big enough to teach three valuable skills: turning mouse clicks into grid cells, keeping game rules separate from drawing, and writing a simple artificial opponent with the minimax algorithm. When you are done you will have a polished two-mode game: play a friend or play an AI that cannot lose.

The board logic and the AI are plain Python and run here. The window code is read-only; run it on your own computer.

Plan the pieces

flowchart LR
  M["Mouse click<br/>(x, y)"] --> CELL["pixel to cell<br/>col = x // size"]
  CELL --> B["Board.play(cell)"]
  B --> W["winner / draw check"]
  W --> UI["draw grid, marks, message"]
  B --> AI["AI picks a move<br/>(minimax)"]
  AI --> B

Clicks go through the board logic; the AI uses the same board interface as a human.

The board class

Store the nine cells in a list: index 0..8, row-major, holding "X", "O" or None. There are only eight ways to win: three rows, three columns and two diagonals.

Python
WIN_LINES = [(0, 1, 2), (3, 4, 5), (6, 7, 8),      # rows
             (0, 3, 6), (1, 4, 7), (2, 5, 8),      # columns
             (0, 4, 8), (2, 4, 6)]                 # diagonals

class Board:
    def __init__(self):
        self.cells = [None] * 9
        self.turn = "X"

    def moves(self):
        return [i for i, c in enumerate(self.cells) if c is None]

    def play(self, index):
        if self.cells[index] is not None or self.winner():
            return False
        self.cells[index] = self.turn
        self.turn = "O" if self.turn == "X" else "X"
        return True

    def undo(self, index):
        self.cells[index] = None
        self.turn = "O" if self.turn == "X" else "X"

    def winner(self):
        for a, b, c in WIN_LINES:
            if self.cells[a] and self.cells[a] == self.cells[b] == self.cells[c]:
                return self.cells[a]
        return None

    def is_draw(self):
        return not self.moves() and not self.winner()

play returns False for an illegal move (occupied cell or finished game), so the GUI can ignore such clicks without special cases. undo is a gift to the AI, as you will see.

Python Play a game through the Board class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Mouse click to cell

If the board is drawn at (left, top) with square cells of SIZE pixels, then a click at (x, y) is in column (x - left) // SIZE and row (y - top) // SIZE, valid only when both are within 0..2:

Python
def cell_from_pixel(x, y, left, top, size):
    col, row = (x - left) // size, (y - top) // size
    if 0 <= col < 3 and 0 <= row < 3:
        return row * 3 + col
    return None

The opposite mapping, from cell to a drawing rectangle, is pygame.Rect(left + col * size, top + row * size, size, size).

Python Pixels to cells

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

An AI that never loses: minimax

Minimax searches the game tree: the computer tries each move, then imagines the opponent's best reply, and so on to the end. A win for the AI scores +1, a loss -1, a draw 0. On the AI's turn it picks the maximum score; on the opponent's turn the opponent picks the minimum (what is worst for the AI). Tic Tac Toe has fewer than 550,000 possible game sequences, so exhaustive search is quick, and caching repeated positions (shown in the next example) makes it instant.

Python
def minimax(board, ai, depth=0):
    win = board.winner()
    if win == ai:
        return 10 - depth            # faster wins score higher
    if win:
        return depth - 10            # slower losses score higher
    if not board.moves():
        return 0
    scores = []
    for m in board.moves():
        board.play(m)
        scores.append(minimax(board, ai, depth + 1))
        board.undo(m)
    return max(scores) if board.turn == ai else min(scores)

def best_move(board):
    ai = board.turn
    best, best_score = None, -99
    for m in board.moves():
        board.play(m)
        score = minimax(board, ai, 1)
        board.undo(m)
        if score > best_score:
            best, best_score = m, score
    return best

The depth adjustment makes the AI prefer quick wins and delay losses, rather than toying with the player. undo lets us reuse a single board instead of copying it thousands of times.

Python Minimax versus a random player

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The memo dictionary remembers positions already scored: different move orders reach the same board, so the cache cuts the work from hundreds of thousands of positions to a few thousand. Across 60 games against a random opponent, the AI never loses. Against a perfect opponent it draws. The first move on an empty board is a tie between several moves; the search picks the first best one.

The Pygame window

Python
import pygame
from ttt_logic import Board, best_move, cell_from_pixel

pygame.init()
SIZE, LEFT, TOP = 140, 40, 100
screen = pygame.display.set_mode((LEFT * 2 + SIZE * 3, TOP + SIZE * 3 + 40))
pygame.display.set_caption("Tic Tac Toe")
font = pygame.font.Font(None, 40)
big = pygame.font.Font(None, 120)
clock = pygame.time.Clock()

board = Board()
vs_ai = True
message = "Your turn (X)"

def restart():
    global board, message
    board, message = Board(), "Your turn (X)"

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_r:
                restart()
            elif event.key == pygame.K_TAB:
                vs_ai = not vs_ai
                restart()
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            cell = cell_from_pixel(*event.pos, LEFT, TOP, SIZE)
            if cell is not None and board.play(cell):
                if vs_ai and not board.winner() and board.moves():
                    board.play(best_move(board))

    winner = board.winner()
    if winner:
        message = f"{winner} wins! Press R"
    elif board.is_draw():
        message = "Draw. Press R"
    else:
        message = f"{board.turn}'s turn" + (" (you)" if vs_ai else "")

    screen.fill((24, 28, 42))
    for i in range(1, 3):
        pygame.draw.line(screen, (90, 100, 130), (LEFT + i * SIZE, TOP), (LEFT + i * SIZE, TOP + 3 * SIZE), 4)
        pygame.draw.line(screen, (90, 100, 130), (LEFT, TOP + i * SIZE), (LEFT + 3 * SIZE, TOP + i * SIZE), 4)
    for i, mark in enumerate(board.cells):
        if mark:
            r = pygame.Rect(LEFT + (i % 3) * SIZE, TOP + (i // 3) * SIZE, SIZE, SIZE)
            colour = (240, 120, 120) if mark == "X" else (120, 200, 240)
            img = big.render(mark, True, colour)
            screen.blit(img, img.get_rect(center=r.center))
    screen.blit(font.render(message, True, (240, 240, 245)), (LEFT, 30))
    screen.blit(font.render("Tab: switch 1P/2P", True, (150, 160, 180)), (LEFT, TOP + 3 * SIZE + 8))
    pygame.display.flip()
    clock.tick(60)
pygame.quit()

The AI answers immediately inside the click handler, which is fine for this game. For slower AIs, run them on a short delay timer so the player can see their own move first.

Ideas to extend it

  • Highlight the winning line: have winner() return the triple too, and draw a thick line through it.
  • Difficulty levels: pick a random move 30% of the time on "easy".
  • Score counter across rounds, saved with JSON.
  • Hover preview: draw a faint mark on the cell under the mouse.
  • Bigger boards (4 by 4, 5 in a row) need smarter search: alpha-beta pruning and a depth limit.
  • Menu with a mode picker using game states.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many winning lines does a 3x3 Tic Tac Toe board have?

    Three rows, three columns and two diagonals make eight.
  2. 2. Given SIZE=120 and LEFT=100, which column does a click at x=330 fall in?

    (330 - 100) // 120 = 1, so column 1.
  3. 3. What does minimax assume about the opponent?

    Minimax maximizes the AI's score on its own turn and minimizes it on the opponent's turn, assuming best play.
  4. 4. Why does the score include 10 - depth for a win?

    Earlier wins get higher scores; for losses the adjustment makes the AI delay defeat.

Summary

  • Keep a Board class with play, undo, winner and moves, independent from Pygame.
  • Convert mouse positions to cells with integer division and a range check.
  • Minimax scores every continuation; with depth-adjusted scores the AI wins fast and never loses.
  • The Pygame layer only draws the grid and marks and forwards clicks to the board.

Next: Algorithm Visualizers