How to Create a Tic-Tac-Toe Game in Python

Tic-Tac-Toe is a simple and fun game that can be easily implemented in Python. In this article, we will build a command-line version of Tic-Tac-Toe step by step.

WhatsApp Group Join Now
Telegram Group Join Now

Steps to Create Tic-Tac-Toe in Python

  1. Create the game board
  2. Take user input
  3. Check for a win or draw
  4. Switch players
  5. Loop until the game ends

Full Python Code for Tic-Tac-Toe

# Initialize the board
def create_board():
    return [' '] * 9

def display_board(board):
    print(f"\n {board[0]} | {board[1]} | {board[2]} ")
    print("---+---+---")
    print(f" {board[3]} | {board[4]} | {board[5]} ")
    print("---+---+---")
    print(f" {board[6]} | {board[7]} | {board[8]} \n")

def check_winner(board, player):
    win_patterns = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]
    return any(board[i] == board[j] == board[k] == player for i, j, k in win_patterns)

def is_draw(board):
    return ' ' not in board

def tic_tac_toe():
    board = create_board()
    player = 'X'
    
    while True:
        display_board(board)
        move = int(input(f"Player {player}, enter your move (1-9): ")) - 1
        
        if board[move] != ' ':
            print("Invalid move! Try again.")
            continue
        
        board[move] = player
        
        if check_winner(board, player):
            display_board(board)
            print(f"Player {player} wins!")
            break
        
        if is_draw(board):
            display_board(board)
            print("It's a draw!")
            break
        
        player = 'O' if player == 'X' else 'X'

if __name__ == "__main__":
    tic_tac_toe()

Explanation of the Tic-Tac-Toe Code

This Python code implements a simple Tic-Tac-Toe game that runs in the command line. Below is a step-by-step explanation of each function and how they work together.

1. Initializing the Board

def create_board():
    return [' '] * 9
  • This function creates an empty 3×3 board using a list with 9 spaces (‘ ‘).
  • The board is represented as a list of 9 elements, corresponding to positions 1-9.

2.Displaying the Board

def display_board(board):
    print(f"\n {board[0]} | {board[1]} | {board[2]} ")
    print("---+---+---")
    print(f" {board[3]} | {board[4]} | {board[5]} ")
    print("---+---+---")
    print(f" {board[6]} | {board[7]} | {board[8]} \n")

This function prints the current state of the board in a structured format.

The board is displayed as

 X | O | X 
---+---+---
 O | X | O 
---+---+---
 X | O | X 

The list indices correspond to positions 1-9 as entered by the player.

3.Checking for a Winner

def check_winner(board, player):
    win_patterns = [(0, 1, 2), (3, 4, 5), (6, 7, 8), 
                    (0, 3, 6), (1, 4, 7), (2, 5, 8), 
                    (0, 4, 8), (2, 4, 6)]
    return any(board[i] == board[j] == board[k] == player for i, j, k in win_patterns)
  • The function checks if a player has won.
  • The winning combinations are stored in win_patterns as tuples representing indices.
  • Example winning patterns:
    • Rows: (0,1,2), (3,4,5), (6,7,8)
    • Columns: (0,3,6), (1,4,7), (2,5,8)
    • Diagonals: (0,4,8), (2,4,6)
  • It checks if all positions in any of these patterns have the same player marker (‘X’ or ‘O’).

4.Checking for a Draw:

def is_draw(board):
    return ' ' not in board

This function checks if the board is full.If there are no empty spaces (' '), and no one has won, it declares a draw.

5.Main Game Logic:

def tic_tac_toe():
    board = create_board()
    player = 'X'
    
    while True:
        display_board(board)
        move = int(input(f"Player {player}, enter your move (1-9): ")) - 1
        
        if board[move] != ' ':
            print("Invalid move! Try again.")
            continue
        
        board[move] = player
        
        if check_winner(board, player):
            display_board(board)
            print(f"Player {player} wins!")
            break
        
        if is_draw(board):
            display_board(board)
            print("It's a draw!")
            break
        
        player = 'O' if player == 'X' else 'X'

Explanation of Game Loop:

  1. Create a fresh board using create_board().
  2. Set the first player as 'X'.
  3. Loop until the game ends:
    • Display the board.
    • Ask the current player to enter a move (1-9).
    • Check if the move is valid (empty space).
    • Update the board with the player’s marker.
    • Check if the player has won.
    • Check if the board is full (draw).
    • Switch players between 'X' and 'O'.

6.Running the Game:

if __name__ == "__main__":
    tic_tac_toe()

The game starts when the script is run.

Game Flow Example

Input & Output:

  1 | 2 | 3 
 ---+---+---
  4 | 5 | 6 
 ---+---+---
  7 | 8 | 9 

Player X, enter your move (1-9): 1

  X | 2 | 3 
 ---+---+---
  4 | 5 | 6 
 ---+---+---
  7 | 8 | 9 

Player O, enter your move (1-9): 5

  X | 2 | 3 
 ---+---+---
  4 | O | 6 
 ---+---+---
  7 | 8 | 9 

Players take turns entering numbers to place X or O.The game continues until someone wins or all spaces are filled.

Conclusion

This Tic-Tac-Toe implementation demonstrates basic programming concepts:

  • Lists for board representation
  • Loops for user input
  • Conditionals for game logic
  • Functions for modular code

You can enhance it by:

  • Adding an AI opponent
  • Improving input validation
  • Creating a graphical version (GUI) with tkinter or pygame.

Leave a Comment