Home Python Project Tic-Tac-Toe using Python

Tic-Tac-Toe using Python

by Akash Maurya

In this article, you’ll learn how to build Tic-Tac-Toe using Python.

This game is very popular amongst all of us and even fun to build as a Python project. I am pretty sure most of us know how to play it but let me give a quick brush up. 

If you are not familiar with Tic-Tac-Toe, play it visually here to understand. Don’t worry, even if you don’t understand it, we are going to see it.

Tic-Tac-Toe using Python

Idea behind the Tic-Tac-Toe

It is a two-player game and consists of a nine-square grid. Each player chooses their move and with O or X and marks their square one at each chance. The player who succeeds in making their marks all in one line whether diagonally, horizontally, or vertically wins. The challenge for the other player is to block the game for their opponent and also to make their chain. 

Let’s see how it’s done

We will now discuss the algorithm to write the code. This algorithm will help you to write code in any programming language of your choice.

  1. Create a board using a 2-dimensional array and initialize each element as empty.
    • You can represent empty using any symbol you like. Here, we are going to use a hyphen. '-'.
  2. Write a function to check whether the board is filled or not.
    • Iterate over the board and return false if the board contains an empty sign or else return true.
  3. Write a function to check whether a player has won or not.
    • We have to check all the possibilities that we discussed in the previous section.
    • Check for all the rows, columns, and two diagonals.
  4. Write a function to show the board as we will show the board multiple times to the users while they are playing.
  5. Write a function to start the game.
    • Select the first turn of the player randomly.
    • Write an infinite loop that breaks when the game is over (either win or draw).
      • Show the board to the user to select the spot for the next move.
      • Ask the user to enter the row and column number.
      • Update the spot with the respective player sign.
      • Check whether the current player won the game or not.
      • If the current player won the game, then print a winning message and break the infinite loop.
      • Next, check whether the board is filled or not.
      • If the board is filled, then print the draw message and break the infinite loop.
    • Finally, show the user the final view of the board.

Source Code With Comment

import random


class TicTacToe:

    def __init__(self):
        self.board = []

    def create_board(self):
        for i in range(3):
            row = []
            for j in range(3):
                row.append('-')
            self.board.append(row)

    def get_random_first_player(self):
        return random.randint(0, 1)

    def fix_spot(self, row, col, player):
        self.board[row][col] = player

    def is_player_win(self, player):
        win = None

        n = len(self.board)

        # checking rows
        for i in range(n):
            win = True
            for j in range(n):
                if self.board[i][j] != player:
                    win = False
                    break
            if win:
                return win

        # checking columns
        for i in range(n):
            win = True
            for j in range(n):
                if self.board[j][i] != player:
                    win = False
                    break
            if win:
                return win

        # checking diagonals
        win = True
        for i in range(n):
            if self.board[i][i] != player:
                win = False
                break
        if win:
            return win

        win = True
        for i in range(n):
            if self.board[i][n - 1 - i] != player:
                win = False
                break
        if win:
            return win
        return False

        for row in self.board:
            for item in row:
                if item == '-':
                    return False
        return True

    def is_board_filled(self):
        for row in self.board:
            for item in row:
                if item == '-':
                    return False
        return True

    def swap_player_turn(self, player):
        return 'X' if player == 'O' else 'O'

    def show_board(self):
        for row in self.board:
            for item in row:
                print(item, end=" ")
            print()

    def start(self):
        self.create_board()

        player = 'X' if self.get_random_first_player() == 1 else 'O'
        while True:
            print(f"Player {player} turn")

            self.show_board()

            # taking user input
            row, col = list(
                map(int, input("Enter row and column numbers to fix spot: ").split()))
            print()

            # fixing the spot
            self.fix_spot(row - 1, col - 1, player)

            # checking whether current player is won or not
            if self.is_player_win(player):
                print(f"Player {player} wins the game!")
                break

            # checking whether the game is draw or not
            if self.is_board_filled():
                print("Match Draw!")
                break

            # swapping the turn
            player = self.swap_player_turn(player)

        # showing the final view of board
        print()
        self.show_board()


# starting the game
tic_tac_toe = TicTacToe()
tic_tac_toe.start()

Output of Tic-Tac-Toe

Player X turn
- - -
- - -
- - -
Enter row and column numbers to fix spot: 1 1

Player O turn
X - -
- - -
- - -
Enter row and column numbers to fix spot: 2 1

Player X turn
X - -
O - -
- - -
Enter row and column numbers to fix spot: 1 2

Player O turn
X X -
O - -
- - -
Enter row and column numbers to fix spot: 1 3

Player X turn
X X O
O - -
- - -
Enter row and column numbers to fix spot: 2 2

Player O turn
X X O
O X -
- - -
Enter row and column numbers to fix spot: 3 3

Player X turn
X X O        
O X -        
- - O
Enter row and column numbers to fix spot: 3 2

Player X wins the game!

X X O
O X -
- X O

Thanks For Scrolling, I hope you liked this article on Tic-Tac-Toe using Python. Hit me up with your views and suggestions in the comment down below.🙌

More Python Projects

You may also like

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.