Learning to program can be both exciting and a bit overwhelming, but building small, fun projects is a great way to understand the basics. One of the classic beginner-friendly projects is Tic Tac Toe, a simple two-player game that’s familiar to almost everyone. If you’re new to Python, this project is perfect for grasping core concepts like loops, conditionals, lists, and functions.
In this article, we’ll walk you through building your own Tic Tac Toe game in Python, step by step. Whether you’re a student, self-taught coder, or just someone curious about programming, this guide is crafted to be easy to follow and rewarding to complete.
What You’ll Learn
- Creating and displaying a game board
- Handling player input
- Checking for a win or draw
- Switching turns between players
Step 1: Setting Up the Game Board
The game board for Tic Tac Toe is a 3×3 grid. We can use a Python list to represent it. Let’s start by creating an empty board:
board = [" " for _ in range(9)]
This creates a list with nine spaces, representing the 3×3 layout. Later, we’ll update the list with 'X'
or 'O'
based on player input.
To make the game interactive, it’s essential to display the board to the players. Here’s a function to print it nicely:
def print_board():
print(board[0] + "|" + board[1] + "|" + board[2])
print("-+-+-")
print(board[3] + "|" + board[4] + "|" + board[5])
print("-+-+-")
print(board[6] + "|" + board[7] + "|" + board[8])
This function visually separates the board into rows and columns, helping players see where they can make their move.
tic tac toe, game board, python code</ai-img]
Step 2: Player Moves
Next, we’ll create a function to handle player input. This function will ask players to choose a position from 1 to 9 on the grid and ensure the selected spot is empty before placing their symbol.
def player_move(icon):
while True:
try:
choice = int(input(f"Player {icon}, choose your move (1-9): ")) - 1
if 0 <= choice < 9 and board[choice] == " ":
board[choice] = icon
break
else:
print("That space is taken or invalid. Try again.")
except ValueError:
print("Invalid input. Please enter a number between 1 and 9.")
This function reduces errors and ensures players only move to legal positions on the board.
Step 3: Checking for a Win
Now let’s implement the logic to check if a player has won the game. There are eight possible ways to win in Tic Tac Toe (three rows, three columns, two diagonals).
def is_victory(icon):
win_combos = [
[0,1,2], [3,4,5], [6,7,8],
[0,3,6], [1,4,7], [2,5,8],
[0,4,8], [2,4,6]
]
for combo in win_combos:
if board[combo[0]] == icon and board[combo[1]] == icon and board[combo[2]] == icon:
return True
return False
This function loops through all the winning combinations and checks if any of them are occupied by the same symbol ('X'
or 'O'
).
Step 4: Detecting a Draw
Sometimes, all positions are filled without anyone winning. Here’s a function that checks for a draw:
def is_draw():
return " " not in board
If no empty spaces are left and no winner has been declared, the game ends in a draw.
Step 5: Putting It All Together
Let’s combine all the pieces into a main game loop that alternates turns between two players:
while True:
print_board()
player_move("X")
if is_victory("X"):
print_board()
print("Player X wins!")
break
elif is_draw():
print_board()
print("It's a draw!")
break
print_board()
player_move("O")
if is_victory("O"):
print_board()
print("Player O wins!")
break
elif is_draw():
print_board()
print("It's a draw!")
break
This loop runs continuously, allowing both players to take turns until the game ends in a win or a draw.
python terminal, beginner project, code output</ai-img]
Conclusion
Congratulations! You’ve just built your very first Python game. Through this project, you’ve learned how lists, functions, conditionals, and loops all work together in a real-world application. Tic Tac Toe may be simple, but it provides a solid foundation for tackling more complex projects in the future.
As your next step, try enhancing the game with features like a restart option, score tracking, or even a basic AI opponent. The possibilities are endless and only limited by your creativity.
Keep coding, stay curious, and most importantly—have fun!