Tic Tac Toe Game (python)

This is a very simple tic-tac-toe game without any GUI.
This game can be played in the command line. 

    Videos from the game:

    • Player won



    • Computer won



    • Draw


    📢RecommendedPlease watch the video first of all. Try to understand the game and the idea behind it and then try to implement  the game on your own first, before looking at the code down below.

    ____________________________________________________

    🎁Code:


    """
        coded by Khaled Badran.
        Date: 09/02/2021
    """

    import os      #to clear the screen/terminal 
    import time    #to make the game look a little bit realistic
    import random  


    PLAYING_FIELD_INPUTS = ["1""2""3""4""5""6""7""8""9"
    clear_screen = lambda: os.system("cls")  # to clear the screen/terminal


    def print_greeting():
        """ clear the screen and greet the player only one time in the beginning of the game
        """
        clear_screen()
        print("\t<<WELCOME TO TIC-TAC-TOE GAME>>\n\t  "end="")
        for i in range(4): #to make the game look a little bit realistic
            time.sleep(0.20)
            print("-----"end="")
        print("")


    def build_playing_field(cell_number=0symbol=""):
        """ build the game grid and return it

        Args:
            cell_number (int): the number of the cell. Defaults to 0.
            symbol (str): the symbol of the players either X or O. Defaults to "".

        Returns:
            String: the game grid including the inputs
        """
        if cell_number:  # to avoid printing the following when we start the game for the first time.
            clear_screen()  
            print("\t<<TIC-TAC-TOE>>"# just to make the game look realistic
            print("\t  ----"end="")
            time.sleep(0.20)
            print("----"end="")
            time.sleep(0.20)
            print("---")

        if symbol != "" and cell_number != 0#if we are not printing the playing_field/ grid for the first time. If the game has already started.   
            cell_index = cell_number - 1
            PLAYING_FIELD_INPUTS[cell_index] = symbol.upper()

        #Build the game grid
        cell_index = 0
        playing_field_structure = "\t  _____________\n"
        for i in range(3): #the game grid cosists of 3 rows
            playing_field_structure += "\t  "
            for j in range(3): #every row consists of 3 cells/ squares
                playing_field_structure += "| " + PLAYING_FIELD_INPUTS[cell_index] + " "
                cell_index += 1
            playing_field_structure += "|\n"
            playing_field_structure += "\t  |___|___|___|\n"

        return playing_field_structure


    def get_symbols():
        """get the symbols of the player and of the computer (X or O)

        Returns:
            tuple of strings: the player symbol and the computer symbol
        """
        player_symbol_choice = str(input("Do you want to be X or O? "))
        while player_symbol_choice.upper() != "X" and player_symbol_choice.upper() != "O"#make sure that the player chooses either X or O
            print("Please enter a valid symbol.\nPlease enter either x or o.")
            player_symbol_choice = str(input())

        if player_symbol_choice.upper() == "X"#if the player chose X then the computer would be O and vise versa. 
            computer_symbol = "O"
        else:
            computer_symbol = "X"

        return player_symbol_choice, computer_symbol


    def get_player_cell_number():
        """ get the number of the cell that the player wants to choose 

        Returns:
            int: number of the cell that the player chose 
        """
        cell_number = 0
        cell_number_str = ""
        valid_numbers = "123456789"

        while cell_number_str not in valid_numbers or len(cell_number_str) != 1#if the input is not valid/ correct
            cell_number_str = str(input("please enter a number of a cell/ square: "))
            if cell_number_str in valid_numbers and len(cell_number_str) == 1:
                cell_number = int(cell_number_str)
                if not is_cell_empty(cell_number): #if the cell is not empty then the player can't choose it.
                    print("The cell number (" + str(cell_number) + ") is not empty.\n" +
                          "please enter a number of an empty cell.")
                    cell_number_str = ""

        return cell_number


    def is_cell_empty(cell_number):
        """determine whether the cell at the given number empty or not 

        Args:
            cell_number (int): number of the cell that the player/computer chose

        Returns:
            boolean: True if the cell is empty. Otherwise False.
        """
        empty_cells = "123456789"
        cell_index = cell_number - 1
        # if the cell has any number then it is empty and can be used
        # if the cell has x or o in it then it is not empty and can't be used.
        return PLAYING_FIELD_INPUTS[cell_index] in empty_cells


    def get_computer_cell_number():
        """get the cell number from the computer

        Returns:
            int: number of the cell that the computer randomly chose
        """
        cell_number = 0
        while cell_number < 1 or cell_number > 9 or not is_cell_empty(cell_number): #choose a random empty cell
            cell_number = random.randint(110

        return cell_number


    def game_over():
        """ check whether the game is over or not.

        Returns:
            boolean: True if the game is over. Else False
        """
        for i in range(3):#if one column is completely filled with X or with O. 
            if PLAYING_FIELD_INPUTS[i] == PLAYING_FIELD_INPUTS[i+3== PLAYING_FIELD_INPUTS[i+6]:
                print_winner(PLAYING_FIELD_INPUTS[i])
                return True

        for i in range(0,9,3):#if one row is completely filled with X or with O.    
            if PLAYING_FIELD_INPUTS[i] == PLAYING_FIELD_INPUTS[i+1== PLAYING_FIELD_INPUTS[i+2]:
                print_winner(PLAYING_FIELD_INPUTS[i])
                return True

        #if one diagonol is completely filled with X or with O.    
        if (PLAYING_FIELD_INPUTS[0== PLAYING_FIELD_INPUTS[4== PLAYING_FIELD_INPUTS[8]):
            print_winner(PLAYING_FIELD_INPUTS[0])
            return True
        if (PLAYING_FIELD_INPUTS[2== PLAYING_FIELD_INPUTS[4== PLAYING_FIELD_INPUTS[6]):
            print_winner(PLAYING_FIELD_INPUTS[2])
            return True

        for i in range(1,10): # if no one won and there is still one empty cell, then the game is not over yet. 
            if is_cell_empty(i):
                return False

        #if there is no empty cells anymore and no one won. 
        print("Game Over")        
        print("Draw")        
        return True


    def print_winner(winner):
        """print who won the game either X or O

        Args:
            winner (str): the winner of the game either X or O
        """
        time.sleep(0.50)
        print("Game Over.")
        print("The winner is " + winner.upper()) 


    def run_the_game():
        """the main function of the game. run the game and end it, if the game is over.  
        """
        print_greeting()
        print(build_playing_field())

        player_symbol, computer_symbol = get_symbols()
        while not game_over():
            cell_number = get_player_cell_number()
            print(build_playing_field(cell_number, player_symbol))
            if game_over():
                break
            cell_number = get_computer_cell_number()
            print("please, wait. It is "+ computer_symbol + "'s Turn ....")
            time.sleep(2)
            print(build_playing_field(cell_number, computer_symbol))
            time.sleep(0.30)
            if game_over():
                break


    run_the_game()

    Output:


    ____________________________________________________



    Comments