Skip to content

Program to Create Tic Tac Toe Game in Python

  • by

Here is Step by Step Procedure to Create Tic Tac Toe Game in Python

Introduction

Tic Tac Toe is a popular two player game that is played on a 3×3 board. The goal of the game is to get three in a row either horizontally, vertically, or diagonally. In this tutorial we will walk you through the steps to create a Tic Tac Toe game in Python.

Step 1: Create the game board

The first step while creating a Tic Tac Toe game in python is to create game board. We will use a 3×3 list to represent board. Each element in the list will represent a square on the board.

To create the game board open up a new Python file and add the following code

board = [    ["-", "-", "-"],
    ["-", "-", "-"],
    ["-", "-", "-"]
]

This code creates a list called board that contains three lists each with three dashes representing empty squares.

Step 2: Print the game board

Next we need to print game board to the console so that players can see the board. To do this add the following code to your Python file

def print_board(board):
    for row in board:
        for square in row:
            print(square, end=" ")
        print()

This code defines a function called print_board that takes board as a parameter and prints each element in the list.

Step 3: Get player input

Now that we have a game board we need to allow the players to make their moves. We will prompt players to enter the row and column they want to place their mark on. To do this add following code to your Python file

def get_player_move():
    row = int(input("Enter the row (0, 1, or 2): "))
    col = int(input("Enter the column (0, 1, or 2): "))
    return row, col

This code define function called get_player_move that prompt player to enter row and column they want to place their mark. The function return tuple containing row and column.

Step 4: Place the player’s mark on the board

Now that we have the player move we need to place their mark on board. We will use “X” to represent the first player mark and an “O” to represent second player’s mark. To place player mark on board add following code to your Python file

def place_marker(board, row, col, marker):
    board[row][col] = marker

This code defines a function called place_marker that takes the board row col and marker as parameters and places the marker on specified row and col of the board.

Step 5: Check for a winner

After each move we need to check if player has won the game. To win the game a player needs to get three in a row either horizontally, vertically, or diagonally. To check for a winner add the following code to your Python file:

def check_for_winner(board):
    # Check for horizontal win
    for row in board:
        if row.count(row[0]) == len(row) and row[0] != "-":
            return True
    
    # Check for vertical win
    for col in range(len(board)):
        if board[0][col] == board[1][col] == board[2][col] and board[0][col] != "-":
            return True
    
    # Check for diagonal win
    if board[0][0] == board[1][1] == board[2][2] and board[0][0] != "-":
        return True
    
    if board[0][2] == board[1][1] == board[2][0] and board[0][2] != "-":
        return True
    
    return False

This code defines a function called check_for_winner that takes the board as a parameter and checks for a horizontal, vertical, or diagonal win. If a win is detected function returns True. Otherwise it returns False.

Step 6: Implement the game loop

Now that we have all functions we need we can implement the game loop. The game loop will continue until there is a winner or board is full. To implement game loop add the following code to your Python file:

def play_game():
    print("Welcome to Tic Tac Toe!")
    board = [
        ["-", "-", "-"],
        ["-", "-", "-"],
        ["-", "-", "-"]
    ]
    player = "X"
    while True:
        print_board(board)
        row, col = get_player_move()
        place_marker(board, row, col, player)
        if check_for_winner(board):
            print_board(board)
            print(player + " wins!")
            break
        if "-" not in board[0] and "-" not in board[1] and "-" not in board[2]:
            print_board(board)
            print("It's a tie!")
            break
        if player == "X":
            player = "O"
        else:
            player = "X"

This code defines a function called play_game that starts the game loop. The function starts by creating a new board and setting the first player to “X”. The loop continues until there is a winner or the board is full. Each iteration of the loop prompts the player for their move places the player’s mark on the board checks for a winner and switches the player.

Step 7: Play the game

Now that we have implemented the game we can play the game by calling the play_game function. Add the following code to the end of your Python file:

play_game()

This code calls the play_game function and starts the game.

Conclusion:

In this tutorial we have walked you through the steps to create a Tic Tac Toe game in Python. We started by creating the game board printing the game board getting player input placing the player’s mark on the board, checking for a winner implementing the game loop and playing the game. We hope you found this tutorial helpful and can use it as a starting point to create your own games in Python.

Also Read:

3 Ways to Implement Binary Search in Python with Programming Examples

Python Useful Links:

Leave a Reply

Your email address will not be published. Required fields are marked *