Wednesday, December 7, 2022
HomeTechHow to Create a Tic-Tac-Toe Game in Python?

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

Let’s use Python to make a basic tic-tac-toe game. You can use this to learn how to organize code and construct game logic.

The human race has a wide variety of entertainment options, one of which is video gaming. There is a wide variety of games available for play on the internet, mobile devices, computers, and other platforms. Our current situation does not permit us to create a game of that scale. Python will be used to develop a command-line interactive tic-tac-toe game.

Play a visual game of Tic Tac Toe to learn the game if you’ve never seen it before. Don’t fret; we’ll see it regardless of whether or not you grasp it.

Tic Tac Toe

There are three parts to this tutorial. This first part will teach you the fundamentals of the classic game of tic-tac-toe. After that, we’ll look at a piece of code that guides us through designing the gameplay mechanics. The description of the structured code is presented at last.

If you are familiar with Tic Tac Toe, you may skip this introduction. Without further ado, then, let’s get into the first part.

Playing Tic Tac Toe

A game will consist of two competitors. Each participant is represented by two signs. In the game, the symbols X and O are utilized universally. In the end, there will be a board with 9 squares on it.

Look at the Tic-Tac-Toe grid.

The rules of play are as follows.

  • Someone will be the first to use one of the empty boxes by placing a sign inside of it.
  • Following this, the second user will position their sign in one of the blank slots.
  • Each player attempts to align their signs in a full row, full column, or full diagonal.
  • The game continues until one player wins or a draw occurs (all boxes are filled with no winning matches).

Please let us show some screenshots from the games.

  • Given the foregoing, it’s clear that player X comes out on top. An X symbol fills each of the diagonal boxes. That player has so been declared the victor.
  • A winning configuration of the same sign can take place in one of eight possible ways. Let’s check through all 8 possible winning configurations.

  • After all the spaces on the board have been filled with no one arrangement being a clear winner, we have a draw. Let’s hope you’ve learned the rules of Tic Tac Toe by now.
  • Right about now is your chance to goof off. To get a feel for the game’s mechanics, you can try them out here. If you already have it, don’t bother.

The algorithm part has to be relocated at this time.

Algorithm

First, we’ll talk about the coding algorithm. You can use this approach to write code in whatever language you like. Allow me to demonstrate the procedure.

  • Make a grid out of a 2D array and fill it with zeroes to start.

There is no one “empty” sign, so feel free to use whatever you like. It’s necessary to put a hyphen here. ‘-‘.

  • Create a method to determine if all available slots are taken.

If the board is empty, return false; otherwise, return true while iterating.

  • Create a method to determine if a player has won a game.

All the possibilities we mentioned in the previous paragraph need to be investigated. Verify that each of the rows, columns, and diagonals has been checked.

  • Since we plan on showing the board to the users several times while they are playing, you need provide a function to display it.
  • The game can be started by creating a special function.

A player’s turn to act should be chosen at random. Program an endless loop that terminates when the game is finished (either win or draw).

  1. Display the board so the player can decide where to play next.
  2. You should prompt the user to enter the row and column they need.
  3. Insert the player’s symbol here.
  4. Find out if the current player won the round.
  5. If the current player won, a winning message should be printed, and the loop should end.
  6. The next step is to see if there is an open spot on the board.
  7. If the board is full, the draw message should be printed, and the loop should end.

Display the board’s final state for the user. It’s possible that you can picture what’s going on. Do not fret if you did not grasp every nuance. Seeing the code will shed light on the situation.

We will now go to the code part. To test the code, I’m assuming you already have Python on your computer.

Code

Please review the code I’ve provided below.

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()

The code’s example results are available for your perusal.

$ python tic_tac_toe.py 
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

Here are the high points that will assist you comprehend the code’s organization.

  1. To keep all the methods in one location, we’ve used a class. It’s convenient enough to be a package that can be used in other programs.
  2. Next, we have separated each duty, no matter how minor, into a distinct role. It facilitates code maintenance for better upkeep.
  3. If we ever wish to release an update for the game, we can use one of the aforementioned methods to do it quickly and easily.

In accordance with the needs of your project, feel free to modify and enhance the aforementioned framework. There are no restrictions on how the code can be structured.

Last Words

Good news! The game you made was from scratch. We don’t normally engage in such a visual game. However, it aids in the development of rational arguments and the preservation of orderly code. Create some engaging games using the same principles. If you think back to your childhood, you’ll be able to locate games that are very comparable.

Best wishes as you dive into the world of coding!

Must Read

Related News