Build an Automatic Tic‑Tac‑Toe Game in Python (Step‑by‑Step)
- Nishadil
- September 06, 2026
- 0 Comments
- 4 minutes read
- 5 Views
- Save
- Follow Topic
A friendly walk‑through of creating a simple, random‑driven Tic‑Tac‑Toe game with Python
Learn how to code a classic Tic‑Tac‑Toe game in Python, from board setup to win detection, using clear explanations and a ready‑to‑run script.
Ever wanted to program the good‑old X‑and‑O game without fiddling with graphics libraries? You’re in luck – Python makes it surprisingly easy. Below is a relaxed, conversational guide that shows exactly how the little script works, why each part matters, and how you can tinker with it later.
First things first: the board. We represent the 3×3 grid as a simple list of nine strings, initially labelled "1" through "9". Those numbers double as prompts for the players, so the screen already tells you where you can place your mark.
Next we give each symbol a friendly name. In this version Player 1 wields "X" and Player 2 gets "O". The players dictionary lets the program print nice messages like “Player 1 (X), choose a position”.
The heart of any Tic‑Tac‑Toe engine is the collection of winning patterns. We store eight tuples – three rows, three columns and the two diagonals – each holding the indices of the three squares that must match for a win. It’s a tiny data‑driven trick that keeps the check_winner function short and sweet.
We also need a way to remember which squares are already taken. A set called occupied does the job nicely; checking membership is O(1) and the code stays readable.
Displaying the board is just a handful of print statements that insert vertical bars and dashes to mimic the classic look. The display_board function clears the console line (well, adds a blank line) and then shows the three rows.
Handling a move is where we talk to the user. The make_move loop asks for input, validates that it’s a number between 1 and 9, and makes sure the spot isn’t already occupied. If anything goes wrong we politely nudge the player to try again – “Please enter a valid number”, “Please choose a position between 1 and 9”, “This position is already occupied”. Those tiny messages add a human touch.
Once a legal move is made, we replace the placeholder on the board with the player’s symbol and add the index to occupied. Then we break out of the loop and hand control back to the main game loop.
The main loop itself is simple: display the board, let the current player move, check for a winner, check for a draw, and finally toggle the player. The winner check runs through each winning combination and uses all() to see if every position in that trio holds the same symbol. If someone wins, we proudly announce it and end the game. If the board fills up with no winner, we declare a draw.
Here’s the full, ready‑to‑run script (copy‑paste it into a .py file and run with Python 3):
board = ["1", "2", "3",
"4", "5", "6",
"7", "8", "9"]
players = {"X": "Player 1", "O": "Player 2"}
winning_combinations = (
(0, 1, 2), (3, 4, 5), (6, 7, 8),
(0, 3, 6), (1, 4, 7), (2, 5, 8),
(0, 4, 8), (2, 4, 6)
)
occupied = set()
def display_board():
print()
print(board[0], "|", board[1], "|", board[2])
print("--+---+--")
print(board[3], "|", board[4], "|", board[5])
print("--+---+--")
print(board[6], "|", board[7], "|", board[8])
print()
def check_winner(symbol):
for combo in winning_combinations:
if all(board[pos] == symbol for pos in combo):
return True
return False
def make_move(symbol):
while True:
choice = input(f"{players[symbol]} ({symbol}), choose a position (1-9): ")
if not choice.isdigit():
print("Please enter a valid number.")
continue
pos = int(choice) - 1
if pos < 0 or pos > 8:
print("Please choose a position between 1 and 9.")
continue
if pos in occupied:
print("This position is already occupied.")
continue
board[pos] = symbol
occupied.add(pos)
break
print("Welcome to Tic‑Tac‑Toe!")
current_player = "X"
while True:
display_board()
make_move(current_player)
if check_winner(current_player):
display_board()
print(players[current_player], "wins!")
break
if len(occupied) == 9:
display_board()
print("It's a draw!")
break
current_player = "O" if current_player == "X" else "X"
print("\nThanks for playing!")
When you run it, you’ll see the board printed, take turns entering numbers, and watch the game announce a win or a draw. It’s a great starter project – you can later spice it up with a simple AI that picks random free squares, or even a minimax algorithm for unbeatable play.
That’s all there is to it. Grab the code, experiment a bit, and enjoy the satisfaction of watching your own Python program decide a classic game of X’s and O’s.
- India
- News
- Technology
- TechnologyNews
- GameDevelopment
- PythonProgramming
- Gameloop
- NumpyLibrary
- DiagonalWinCheck
- WinConditions
- EvaluateGameStatus
- TicTacToe
- RandomPlacement
- PlayerTurns
- ColumnWinCheck
- RowWinCheck
- 3x3Board
- GameLogic
- RandomModule
- AutomaticTicTacToe
- PythonGameImplementation
- PythonTicTacToe
- BoardGameImplementation
- RandomNumberTicTacToe
- SimplePythonGame
Editorial note: Nishadil may use AI assistance for news drafting and formatting. Readers can report issues from this page, and material corrections are reviewed under our editorial standards.