Create a Tic Tac Toe Game Using Python Pygame

Tic tac toe is the first game I build with anyone who’s new to Pygame, because it needs every core idea and still fits in about 150 lines.

Creating a game with Python and Pygame comes down to four jobs: open a window, run a loop that reads mouse and keyboard events, redraw the board every frame and check the rules after each move. Here’s the finished game after three real rounds:

Tic tac toe game window built with Python Pygame showing X winning on the diagonal with a red line and the score X 2, O 0, Draw 1
The finished game: X takes the diagonal in round three, and the bar keeps the running score.

In this tutorial, I’ll build that pygame tic tac toe game one step at a time. Each step adds a few lines to the same file, and you’ll run it after every step.

  • A 600 x 680 window with a 3 x 3 grid and a status bar
  • Mouse clicks that place X and O in empty squares only
  • Win and draw detection with a red winning line
  • A score, an R key to restart, and an optional computer player

Before You Start: install Pygame for the tic tac toe game

You need Python 3.9 or newer and one package. I used pygame-ce (the community edition), installed with pip install pygame-ce; it’s imported as pygame, exactly like the original package.

Important: install either pygame or pygame-ce, not both. They share the same import name, so a second install overwrites the first one’s files. A Python virtual environment keeps a game project clean.

python -m venv venv
venv\Scripts\activate
pip install pygame-ce

Then check that Python can import it:

import platform
import pygame

print("Python:", platform.python_version())
print("Pygame:", pygame.version.ver)
print("SDL:", ".".join(str(n) for n in pygame.get_sdl_version()))

Output:

pygame-ce 2.5.8 (SDL 2.32.10, Python 3.12.5)
Python: 3.12.5
Pygame: 2.5.8
SDL: 2.32.10
Command Prompt running a script that prints the Python, pygame-ce and SDL versions
Importing pygame-ce prints its banner first, then the script shows the Python, Pygame and SDL versions.

Mine reported Python 3.12.5, Pygame 2.5.8 and SDL 2.32.10. These are the settings the whole game uses, so you can change one number later and everything follows:

SettingValueWhy
CELL200 pxOne square of the board
BOARD600 px3 squares across and down
BAR80 pxStatus bar for turn, result and score
Window600 x 680 pxBOARD wide, BOARD + BAR tall
PlayersX then OX always opens a round
Restart keyRClears the board and keeps the score

Step 1: Open the Pygame window and run the game loop

Every Pygame game is a loop: read events, update the game, draw a frame, repeat. Create tictactoe.py with the settings and a loop that only paints the background (it’s a plain Python while loop that stops when you close the window):

import sys
import pygame

CELL = 200                    # each square is 200 x 200 pixels
BOARD = CELL * 3              # the 3 x 3 board is 600 pixels wide
BAR = 80                      # status bar under the board
WIDTH, HEIGHT = BOARD, BOARD + BAR

BG = (28, 170, 156)           # teal background
GRID = (21, 128, 118)         # darker teal grid lines
X_COLOR = (52, 58, 64)        # charcoal X
O_COLOR = (242, 235, 211)     # cream O
WIN_COLOR = (230, 57, 70)     # red winning line
BAR_COLOR = (16, 42, 67)      # navy status bar
TEXT = (255, 255, 255)

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Tic Tac Toe - Pygame")
clock = pygame.time.Clock()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:       # the window's X button
            running = False

    screen.fill(BG)
    pygame.display.flip()                   # show the finished frame
    clock.tick(60)                          # at most 60 frames per second

pygame.quit()
sys.exit()

pygame.display.flip() pushes the frame you drew to the screen, and clock.tick(60) caps the loop at 60 frames per second, so the game doesn’t burn a whole CPU core.

After the loop, pygame.quit() closes the window and sys.exit() ends the Python program.

Empty teal Pygame window titled Tic Tac Toe - Pygame opened by the game loop
The real window: 600 x 680 pixels of teal, with the caption from set_caption().

Checkpoint: run python tictactoe.py. A teal window titled “Tic Tac Toe – Pygame” opens, and the X button closes it cleanly.

Step 2: Draw the tic tac toe grid with pygame.draw.line()

The grid is four lines: two horizontal at y = 200 and 400, and two vertical at x = 200 and 400. Put the drawing in a function so the loop can call it every frame:

def draw_grid():
    screen.fill(BG)
    for i in (1, 2):
        # horizontal line at y = 200 and y = 400
        pygame.draw.line(screen, GRID, (0, i * CELL), (BOARD, i * CELL), 10)
        # vertical line at x = 200 and x = 400
        pygame.draw.line(screen, GRID, (i * CELL, 0), (i * CELL, BOARD), 10)

In the loop, replace screen.fill(BG) with draw_grid(). Pygame doesn’t remember what’s on screen, so we repaint the background first and the lines on top, every frame.

Pygame window with a 3 x 3 tic tac toe grid drawn with pygame.draw.line on a teal background
Two horizontal and two vertical lines split the top 600 pixels into nine squares.

If you’ve drawn shapes in Tkinter before, this is the same idea as a canvas; my Tkinter canvas guide shows the event-driven version of it.

Step 3: Place X and O with mouse clicks in Pygame

Now the game needs memory. The board is a list of three lists, one per row, holding None, "X" or "O"; that’s the usual way to initialize a 2D array in Python without NumPy.

board = [[None] * 3 for _ in range(3)]      # None, "X" or "O"
player = "X"                                # X always moves first


def cell_from_pos(pos):
    """Turn a mouse position into (row, col), or None for the status bar."""
    x, y = pos
    if y >= BOARD:
        return None
    return y // CELL, x // CELL


def draw_marks():
    for row in range(3):
        for col in range(3):
            cx = col * CELL + CELL // 2     # center of this square
            cy = row * CELL + CELL // 2
            if board[row][col] == "X":
                d = 55
                pygame.draw.line(screen, X_COLOR, (cx - d, cy - d), (cx + d, cy + d), 20)
                pygame.draw.line(screen, X_COLOR, (cx - d, cy + d), (cx + d, cy - d), 20)
            elif board[row][col] == "O":
                pygame.draw.circle(screen, O_COLOR, (cx, cy), 60, 14)

Build the board with a list comprehension, not [[None] * 3] * 3. That shortcut makes three references to one row, so an X in the top row would also appear in the other two rows.

cell_from_pos() uses floor division: a click at x = 330, y = 120 gives row 0, column 1. The status bar check matters, and you’ll see why in the troubleshooting section.

draw_marks() walks every square with two nested loops (the same pattern as when you iterate through a 2D array) and draws an X as two thick lines or an O as a ring. Here’s the loop that handles left clicks:

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            cell = cell_from_pos(event.pos)
            if cell and board[cell[0]][cell[1]] is None:    # empty square only
                row, col = cell
                board[row][col] = player
                player = "O" if player == "X" else "X"

    draw_grid()
    draw_marks()
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
sys.exit()
Pygame tic tac toe board with X in the center and top-right corner and O in the top-left and bottom-left squares
Six scripted clicks: four landed, a repeat click on the center and a click on the bar were ignored.

Checkpoint: my demo clicked the center, top-left, top-right, bottom-left, the center again and the status bar. The board held exactly four marks, [['O', None, 'X'], [None, 'X', None], ['O', None, None]], and it was X’s turn.

Step 4: Check for a tic tac toe winner or a draw

There are only eight ways to win: three rows, three columns and two diagonals. List them once as cell coordinates, then test each line after every move:

LINES = [[(r, 0), (r, 1), (r, 2)] for r in range(3)]            # 3 rows
LINES += [[(0, c), (1, c), (2, c)] for c in range(3)]           # 3 columns
LINES += [[(0, 0), (1, 1), (2, 2)], [(0, 2), (1, 1), (2, 0)]]   # 2 diagonals

winner, win_line = None, None


def check_winner(board):
    """Return ("X" or "O", winning cells), ("Draw", None) or (None, None)."""
    for line in LINES:
        a, b, c = (board[r][col] for r, col in line)
        if a is not None and a == b == c:
            return a, line
    if all(cell is not None for row in board for cell in row):
        return "Draw", None
    return None, None


def draw_win_line(line):
    (r1, c1), (r2, c2) = line[0], line[-1]
    start = (c1 * CELL + CELL // 2, r1 * CELL + CELL // 2)
    end = (c2 * CELL + CELL // 2, r2 * CELL + CELL // 2)
    pygame.draw.line(screen, WIN_COLOR, start, end, 12)

check_winner() returns two things at once, the winning mark and its line (see returning multiple values from a function). It gives "Draw" for a full board and None while the game is on.

The draw test runs Python all() over a generator that walks the rows and then the cells, the same trick used to flatten a list of lists.

Before wiring it into the window, test the logic by itself. That’s much faster than clicking through games:

LINES = [[(r, 0), (r, 1), (r, 2)] for r in range(3)]            # 3 rows
LINES += [[(0, c), (1, c), (2, c)] for c in range(3)]           # 3 columns
LINES += [[(0, 0), (1, 1), (2, 2)], [(0, 2), (1, 1), (2, 0)]]   # 2 diagonals



def check_winner(board):
    """Return ("X" or "O", winning cells), ("Draw", None) or (None, None)."""
    for line in LINES:
        a, b, c = (board[r][col] for r, col in line)
        if a is not None and a == b == c:
            return a, line
    if all(cell is not None for row in board for cell in row):
        return "Draw", None
    return None, None

games = {
    "Top row":    [["X", "X", "X"], ["O", "O", None], [None, None, None]],
    "Diagonal":   [["O", "X", "X"], ["X", "O", None], [None, None, "O"]],
    "Full board": [["X", "O", "X"], ["X", "O", "O"], ["O", "X", "X"]],
    "In play":    [["X", None, None], [None, "O", None], [None, None, None]],
}
for name, b in games.items():
    who, line = check_winner(b)
    print(f"{name:<11} -> {who}  {line}")

Output:

Top row     -> X  [(0, 0), (0, 1), (0, 2)]
Diagonal    -> O  [(0, 0), (1, 1), (2, 2)]
Full board  -> Draw  None
In play