Build a Tic-Tac-Toe Game with Python
Published: 2022-03-21 02:37:05


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5e87zkiy8z6aru2257mm.jpg)

As kids, the majority of us loved playing games like tic-tac-toe, sudoku, snake xenzia and the likes. So what better way to solidify your python knowledge than building one of these games.

In this article, I will walk you through how to build a Tic-Tac-Toe game from scratch with just the basics of python.

#About the Game


We are going to build a tic-tac-toe game that can be played between yourself and the computer. It can be played on any python IDLE or Jupyter notebook.  

Here is how the game works - Initially, we’ll make an empty game board and then the program randomly decides who plays first ( you or the computer). Then we take inputs from the players (x or o) in turns and the program checks for a win, lose or tie. Whatever the outcome of the game, the program asks the player if they would like to go another round.

To learn more about the rules of playing the tic-tac-toe game, refer to [Rules of the Game](https://www.exploratorium.edu/brain_explorer/tictactoe.html).

Now, let’s get started.

#Tools
Ensure you have Jupyter notebook, Pycharm or any other good python IDE installed on your system.

#Steps

## 1. Create a function that displays the board.

```python
from IPython.display import clear_output
board = ['#',' ',' ',' ',' ',' ',' ',' ',' ',' '] #To create an empty board

def display(board):  #here comes the function
    clear_output()
    print('  |   | ')
    print(board[1]+' | '+board[2]+' | '+board[3])
    print('  |   | ')
    print("----------")
    print('  |   | ')
    print(board[4]+' | '+board[5]+' | '+board[6])
    print('  |   | ')
    print("----------")
    print('  |   | ')
    print(board[7]+' | '+board[8]+' | '+board[9])
    print('  |   | ') 

```   
The purpose of this function is to act like a screen that displays each time a input is entered either by you or the computer.
   You can use IPython.display clear_output() syntax to clear   the output of a cell. This will make the console look neat but *clear_output()* only works in a Jupyter notebook. For other IDLE use *print( ‘\n’ * 100 )* instead.


## 2. Write a function that asks a player for his input either ‘X’ or ‘O’ and returns a tuple.

```python
def player_input():
    marker = ''
    player1 = ''
    computer = ''
    while not (marker == 'X' or marker == 'O'):
        marker = input("Please select a marker 'x' or 'o': ").upper()
        if (marker != 'X') or (marker != 'O'):
            clear_output()
        if marker == 'X':
            print(f"You are '{marker}' '")
            print("Computer is 'O'")
            player1,computer = 'X','O'
        elif marker == 'O':
            print(f"You are '{marker}' '")
            print("Computer is 'X'")
            player1,computer = 'O','X'
    return player1,computer
```
In this function we first created empty variables marker,player1 and computer. Next, the program asks for an input and stores this input in a marker as long as the player enters 'x' or 'o' hence, the essence of the while loop. The '.upper()' method just returns capitalized version of the input as this would make the game look nicer. The function of the next lines of codes is to print what you entered as your marker('x' or 'o') and make the computer the other. Then at the end of this function we return 'X' and 'O' as a tuple and save them in player1,computer.


## 3. A function to show the player where to place his marker(‘X’ or ‘O’).

``` python
def display_position_board(): #to show user where to place a marker
    print("Please select a position to place your marker")
    print('  |   | ')
    print(f"{1} | {2} | {3}")
    print('  |   | ')
    print("----------")
    print('  |   | ')
    print(f"{4} | {5} | {6}")
    print('  |   | ')
    print("----------")
    print('  |   | ')
    print(f"{7} | {8} | {9}")
    print('  |   | ')

```

The purpose of this function is to clearly define what value each position represents, in order to avoid confusion. It looks just like this 
![positions on board](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m5hhvaebj99epcv6p3ko.jpg)
With this, the player is well aware of what position each number represents.


## 4. Create a function that collects the position of where the player has chosen to place the marker,As shown earlier the position should be between 1 to 9.

```python
def position_chioce(): #a function that collects the users position
    chioce = ''
    while chioce not in range(1,10):
        chioce = int(input("Select a position to place your marker(1-9): "))
        if chioce not in range(1,10):
            clear_output()
    return chioce

```

Here, we want to get the user select a position to place his earlier chosen marker. Since the only possible positions are between 1 to 9 we would use a while loop to keep asking for a position until the user enters something valid.


## 5.  Write a function that takes in the board,a marker ('X' or 'O'), and a desired position (number 1-9) as arguments and assigns the marker to the board.

```python
def placing_input(board,position,marker): #to place a marker on the selected position
    board[position] = marker

```

The board is passed in as an argument so we can easily access the empty board we created earlier at the beginning. The next argument is the position we want to place our input then the last argument is the input itself. It looks just like this

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fuakgxn8j0ii34j6yidk.jpg)

## 6. Creates a function that takes in the board and checks if we have a winner.

There are 8 possible ways for a winner to emerge which is clearly explained her [Rules of the Game](https://www.exploratorium.edu/brain_explorer/tictactoe.html). This function checks if any of these ways is True.

```python
def win_check(board,mark):
    
    return ((board[7] == mark and board[8] == mark and board[9] == mark) or # across the bottom
    (board[4] == mark and board[5] == mark and board[6] == mark) or # across the middle
    (board[1] == mark and board[2] == mark and board[3] == mark) or # across the top
    (board[7] == mark and board[4] == mark and board[1] == mark) or # down the left side
    (board[8] == mark and board[5] == mark and board[2] == mark) or # down the middle
    (board[9] == mark and board[6] == mark and board[3] == mark) or # down the right side
    (board[7] == mark and board[5] == mark and board[3] == mark) or # diagonal
    (board[9] == mark and board[5] == mark and board[1] == mark)) # diagonal

```


## 7. Write a function that uses the random module to randomly decide who goes first.

First off we need to import the module ('import random'), next is to define the function *whose_turn()*. This function should return either 1 or 2 at random each time it is ran where 1 means player1 plays first and 2 means computer makes the first move. See code below:

```python
import random   #imports the random library

def whose_turn():
    r = random.randint(1,2) #randomly selects who goes first
    if r == 1:
        return "player1"  #player1 goes first
    else:
        return "computer" #computer goes first

```


## 8. Write a function to check if we have an empty space or not.

```python 
def empty_space(position,board):
    return board[position] == ' '
```
The function returns True if we have an empty space and Fals otherwise.


## 9. Write a function that checks if the board is full and returns a boolean value. True if full, and False otherwise.

``` python
def full_board_check(board): #this checks if the board is full
    for i in range(1,10):
        if board[i] == ' ':
            return False
    return True

```


## 10. Create a function that randomly selects positions for the computer to place its marker

```python
import random   #imports the random library


def computer():  #this function randomly generates numbers between 1 to 9
    return random.randint(1,9)

```

## 11. Bringing it all together

The last piece of the puzzle is putting all these together using if, elif, else statements, while and for loops in order to combine these functions together. This is where the bulk of the work is as it tests your thinking process as a programmer. Time to show you my entire code.

```python
print("Welcome to my Tic Tac Toe Game")

play = True

while play:
    answer = ' '

    board = ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']

    player1_marker, computer_marker = player_input()

    display_position_board()

    turn = whose_turn()

    game_on = True

    while game_on:

        if turn == "player1":
            position = position_chioce()
            if empty_space(position, board) == True:
                placing_input(board, position, player1_marker)
                display(board)
                turn = "computer"

                if win_check(board, player1_marker):
                    display(board)
                    print("Congratulations you have won")
                    answer = input("Do you want to go another round(y/n):")
                    if answer == 'n':
                        game_on = False
                        play = False
                    else:
                        game_on = False
                        play = True


                else:
                    if full_board_check(board):
                        display(board)
                        print("The game is a draw")
                        answer = input("Do you want to go another round(y/n):")
                        if answer == 'n':
                            game_on = False
                            play = False
                        else:
                            game_on = False
                            play = True
                    else:
                        turn = "computer"

            elif empty_space(position, board) == False:
                clear_output()
                display(board)
                print('Please select a valid position')
                turn = "player1"
                continue


        else:
            if turn == "computer":
                position = computer()
                if empty_space(position, board) == True:
                    placing_input(board, position, computer_marker)
                    display(board)
                    turn = "player1"

                    if win_check(board, computer_marker):
                        display(board)
                        print("Sorry you loose")
                        answer = input("Do you want to go another round(y/n):")
                        if answer == 'n':
                            game_on = False
                            play = False
                        else:
                            game_on = False
                            play = True

                    elif full_board_check(board):
                        display(board)
                        print("We have a draw")
                        answer = input("Do you want to go another round(y/n):")
                        if answer == 'n':
                            game_on = False
                            play = False
                        else:
                            game_on = False
                            play = True
                    turn = "player1"

print("Thanks for playing")

```

#Conclusion.

We were able to build a powerful python project using the basics of python programming. After building this project we now have a clear understanding of how python scripting works, control flow statements  looping and functions.
	You can find my Jupyter notebook or .py file for the source code on [GitHub](https://github.com/chizzyedoka/Tic_Tac_Toe_game/find/main)