Tic Tac Toe is the classic first board game to code, and for good reason: the whole board fits in one Python list of nine squares, and every rule is a short if statement. This version puts you (X) against a computer player (O) that tries to win, blocks your lines and grabs the middle when it can.
Press Play to try the finished game in the console below. Then follow the build steps, and finish with three coding challenges that check your code automatically.
Play Tic Tac Toe
Press ▶ Play to start the game. When it asks you something, type your answer and press Enter.
View and edit the code (73 lines)
How to play
- The squares are numbered 1 to 9, left to right, top to bottom.
- Type a number to place your X. The computer answers with an O.
- Three in a row (across, down or diagonal) wins. A full board with no line is a draw.
The complete Tic Tac Toe code
Here is the whole program (73 lines). It only uses Python's standard library, so it runs anywhere Python 3 is installed.
import random
# The board is a list of 9 squares: index 0 is the top-left, 8 is the bottom-right.
board = [" "] * 9
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
def show(board):
print()
for r in range(3):
print(" " + " | ".join(board[r * 3:r * 3 + 3]))
if r < 2:
print("---+---+---")
print()
def winner(board):
for a, b, c in LINES:
if board[a] != " " and board[a] == board[b] == board[c]:
return board[a]
return None
def free_squares(board):
return [i for i in range(9) if board[i] == " "]
def computer_move(board):
# 1. win if we can, 2. block X, 3. take the centre, 4. pick any free square
for mark in ["O", "X"]:
for i in free_squares(board):
board[i] = mark
found = winner(board) == mark
board[i] = " "
if found:
return i
if board[4] == " ":
return 4
return random.choice(free_squares(board))
print("TIC TAC TOE - you are X, the computer is O")
print("Squares: 1 | 2 | 3 then 4 5 6, then 7 8 9")
show(board)
while True:
move = input("Your move (1-9): ").strip()
if not move.isdigit() or not 1 <= int(move) <= 9:
print("Type a number from 1 to 9.")
continue
square = int(move) - 1
if board[square] != " ":
print("That square is taken.")
continue
board[square] = "X"
if winner(board) or not free_squares(board):
break
spot = computer_move(board)
board[spot] = "O"
print(f"The computer takes square {spot + 1}.")
show(board)
if winner(board) or not free_squares(board):
break
show(board)
if winner(board) == "X":
print("You win! Three in a row.")
elif winner(board) == "O":
print("The computer wins this time.")
else:
print("It's a draw. Nobody got three in a row.")How the Tic Tac Toe game works, step by step
01Store the board in a list
Nine squares, nine items. [" "] * 9 makes a list of nine spaces, and the square a player picks (1-9) is the list index plus one. Keeping the board as plain data means every other part of the game is just a function that reads or changes that list.
board = [" "] * 9
board[4] = "X" # the centre square02Print the grid
Each row is a slice of three items. " | ".join(...) glues them together with bars, and a divider line goes between rows.
for r in range(3):
print(" " + " | ".join(board[r * 3:r * 3 + 3]))03Check every winning line
There are only eight ways to win, so we list them as tuples of indexes. A line wins when its three squares hold the same mark and are not empty. Python lets you chain comparisons: a == b == c.
for a, b, c in LINES:
if board[a] != " " and board[a] == board[b] == board[c]:
return board[a]04Read the player's move safely
input() always returns text, so we check .isdigit() before calling int(), then make sure the square is free. continue jumps back to ask again.
move = input("Your move (1-9): ").strip()
if not move.isdigit() or not 1 <= int(move) <= 9:
continue05Give the computer a plan
The computer tries each free square: if placing an O there wins, it plays it; if placing an X there would let you win, it blocks. Otherwise it takes the centre, or a random square with random.choice().
for mark in ["O", "X"]:
for i in free_squares(board):
board[i] = mark
found = winner(board) == mark
board[i] = " "What you'll learn
- Lists as a game board and list slicing
- Tuples and unpacking in a
forloop - Writing small functions that return values
- Validating
input()with.isdigit() - A simple game AI with nested loops
Python concepts in this game:
Tic Tac Toe coding challenges
Write the key parts of the game yourself. Press Run to try your code and Check to test it. Each challenge you pass earns a star (saved in this browser).
Print one row
Write row_text(board, r) that returns row r (0, 1 or 2) as text like " X | O | X ": a space, the three squares joined by " | ", and a space.
Hint
Row r starts at index r * 3. The slice board[r * 3:r * 3 + 3] gives its three squares.
Show a solution
def row_text(board, r):
return " " + " | ".join(board[r * 3:r * 3 + 3]) + " "
print(row_text(["X", "O", "X", " ", "X", " ", "O", " ", " "], 0))Find the winner
Finish winner(board): return "X" or "O" if that mark fills any line in LINES, otherwise return None.
Hint
A line wins when the first square isn't a space and all three are equal: board[a] == board[b] == board[c].
Show a solution
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 LINES:
if board[a] != " " and board[a] == board[b] == board[c]:
return board[a]
return None
print(winner(["X", "X", "X", "O", "O", " ", " ", " ", " "]))List the free squares
Write free_squares(board) that returns the square numbers 1 to 9 (not indexes) that are still empty, smallest first.
Hint
Loop over range(9) and append i + 1 when board[i] == " ".
Show a solution
def free_squares(board):
free = []
for i in range(9):
if board[i] == " ":
free.append(i + 1)
return free
print(free_squares(["X", " ", "O", " ", "X", " ", " ", " ", "O"]))Make it your own
Once your challenges pass, try one of these upgrades:
- Let two people play each other instead of the computer.
- Keep a running score over several rounds.
- Make the computer unbeatable with the minimax algorithm.
- Grow the board to 4×4 and four in a row.
Frequently asked questions
How do you make Tic Tac Toe in Python?
Store the board as a list of nine strings, print it in three rows, read moves with input(), and check the eight winning lines after every move. The full program on this page is about 80 lines.
How does the computer player choose a move?
It tests every free square: first for a move that wins, then for a square that blocks your win. If neither exists it takes the centre, then a random free square.
Can I run this Tic Tac Toe code without installing Python?
Yes. Press Play on this page and the real Python program runs in your browser. To run it on your computer, save it as tictactoe.py and run python tictactoe.py.