Tic Tac Toe Game in Python Amazing Mini Project

6 min read

The best way to learn python is by doing projects. So hello python lovers today we develop Tic Tac Toe Game in Python. Mini projects are best practice for beginners to get more interest in coding. So let’s code a tic tac toe game in python.

What we gonna do?

Two players will play the tic tac toe game. First, we ask the user to enter their name. Initially, we print the empty board and then we’ll take the user input and we’ll check for the winning condition and if the whole board gets filled and no one wins, we’ll declare the result as “Tie” and ask users if they want to restart the game.

Which python concepts are covered?

  • List
  • If-else
  • for loop
  • functions
  • break statement

How does the game work?

The board is similar to the number keyboard. So, players only need to enter a position number to put their character (X or O).

tic tac toe game in python

Let’s code Tic Tac Toe Game in Python

First, we are using python List to create a tic tac toe board. We’ll create a list of length 9. Initially, all elements are filled with a blank character (” “). Each place of the list will represent a block in the board and its corresponding value will represent the move made by a player. We’ll create a function draw_board() which we can use every time we want to print the updated board in the game.

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

def draw_board(board):
    print(board[7] + " |" + board[8] + " |" + board[9])
    print("--+--+--")
    print(board[4] + " |" + board[5] + " |" + board[6])
    print("--+--+--")
    print(board[1] + " |" + board[2] + " |" + board[3])

Initially board will look like this,

  |  | 
--+--+--
  |  | 
--+--+--
  |  | 

As the game start, we ask players to enter their names. And we’ll store names in and player2 variable. So, character X and O assign to player1 and player2 respectively.

player1 = input("Enter 1st Player name: ")
player2 = input("Enter 2nd Player name: ")

print(player1 + ": X |" + player2 + ": O")

Now, in the main logic, we’ll take the input from the first player and check if the input is a valid move or not. If the block that player requests to move to is valid, we’ll fill that block else we’ll ask the user to choose another block.

def game():
    turn = "X"
    count = 0
    player_turn = player1

    for i in range(10):
        draw_board(board)
        print("It's your turn, " + player_turn + ". Move to which place?")
        move = eval(input())

        if board[move] == " ":
            board[move] = turn
            count += 1
        else:
            print("That place is already filled.\nMove to which place?")
            continue

Now, to check the winning condition, we’ll check a total of 8 conditions and whichever player has made the last move, we’ll declare that player as a winner. And if no one wins, we’ll declare “Tie”.

if count >= 5:
            if board[7] == board[8] == board[9] != " ":  # across the top
                declare_winner(turn)
                break
            elif board[4] == board[5] == board[6] != " ":  # across the middle
                declare_winner(turn)
                break
            elif board[1] == board[2] == board[3] != " ":  # across the bottom
                declare_winner(turn)
                break
            elif board[1] == board[4] == board[7] != " ":  # down the left side
                declare_winner(turn)
                break
            elif board[2] == board[5] == board[8] != " ":  # down the middle
                declare_winner(turn)
                break
            elif board[3] == board[6] == board[9] != " ":  # down the right side
                declare_winner(turn)
                break
            elif board[7] == board[5] == board[3] != " ":  # diagonal
                declare_winner(turn)
                break
            elif board[1] == board[5] == board[9] != " ":  # diagonal
                declare_winner(turn)
                break

        # If neither X nor O wins and the board is full, we'll declare the result as 'tie'.
        if count == 9:
            print("\nGame Over.\n")
            print("It's a Tie!!")
        # Now we have to change the player after every move.
        if turn == "X":
            turn = "O"
            player_turn = player2
        else:
            turn = "X"
            player_turn = player1

Inside every condition, we call another function declare_winner(). If the condition will become true mean player wins the game and this function will be called.

def declare_winner(turn):
    draw_board(board)
    print("\nGame Over.\n")
    if turn == "X":
        print(" **** " + player1 + " won ****")
    else:
        print(" **** " + player2 + " won ****")

And once a for loop condition will become false or game is over then we ask the user to play again.

restart = input("\nDo want to play Again?(y/n): ")
    if restart == "y" or restart == "Y":
        for element in board:
            board[board.index(element)] = " "
        game()

Your tic tac toe in python is ready now.

The full code

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


def draw_board(board):
    print(board[7] + " |" + board[8] + " |" + board[9])
    print("--+--+--")
    print(board[4] + " |" + board[5] + " |" + board[6])
    print("--+--+--")
    print(board[1] + " |" + board[2] + " |" + board[3])


player1 = input("Enter 1st Player name: ")
player2 = input("Enter 2nd Player name: ")

print(player1 + ": X |" + player2 + ": O")


def game():
    turn = "X"
    count = 0
    player_turn = player1

    for i in range(10):
        draw_board(board)
        print("It's your turn, " + player_turn + ". Move to which place?")
        move = eval(input())

        if board[move] == " ":
            board[move] = turn
            count += 1
        else:
            print("That place is already filled.\nMove to which place?")
            continue

        if count >= 5:
            if board[7] == board[8] == board[9] != " ":  # across the top
                declare_winner(turn)
                break
            elif board[4] == board[5] == board[6] != " ":  # across the middle
                declare_winner(turn)
                break
            elif board[1] == board[2] == board[3] != " ":  # across the bottom
                declare_winner(turn)
                break
            elif board[1] == board[4] == board[7] != " ":  # down the left side
                declare_winner(turn)
                break
            elif board[2] == board[5] == board[8] != " ":  # down the middle
                declare_winner(turn)
                break
            elif board[3] == board[6] == board[9] != " ":  # down the right side
                declare_winner(turn)
                break
            elif board[7] == board[5] == board[3] != " ":  # diagonal
                declare_winner(turn)
                break
            elif board[1] == board[5] == board[9] != " ":  # diagonal
                declare_winner(turn)
                break

        # If neither X nor O wins and the board is full, we'll declare the result as 'tie'.
        if count == 9:
            print("\nGame Over.\n")
            print("It's a Tie!!")
        # Now we have to change the player after every move.
        if turn == "X":
            turn = "O"
            player_turn = player2
        else:
            turn = "X"
            player_turn = player1

    # Now we will ask if player wants to restart the game or not.
    restart = input("\nDo want to play Again?(y/n): ")
    if restart == "y" or restart == "Y":
        for element in board:
            board[board.index(element)] = " "
        game()


def declare_winner(turn):
    draw_board(board)
    print("\nGame Over.\n")
    if turn == "X":
        print(" **** " + player1 + " won ****")
    else:
        print(" **** " + player2 + " won ****")


if __name__ == "__main__":
    game()

# follow @code_snail on instagram

Output

Enter 1st Player name: iron-man
Enter 2nd Player name: spider-man
iron-man: X |spider-man: O
  |  | 
--+--+--
  |  | 
--+--+--
  |  | 
It's your turn, iron-man. Move to which place?
1
  |  | 
--+--+--
  |  | 
--+--+--
X |  | 
It's your turn, spider-man. Move to which place?
7
O |  | 
--+--+--
  |  | 
--+--+--
X |  | 
It's your turn, iron-man. Move to which place?
3
O |  | 
--+--+--
  |  | 
--+--+--
X |  |X
It's your turn, spider-man. Move to which place?
5
O |  | 
--+--+--
  |O | 
--+--+--
X |  |X
It's your turn, iron-man. Move to which place?
2
O |  | 
--+--+--
  |O | 
--+--+--
X |X |X

Game Over.

 **** iron-man won ****

Do want to play Again?(y/n): n

reference: The Classic Tic-Tac-Toe Game in Python 3

Hope you enjoyed it. Now It’s your turn to make your own tic tac toe game in python with some modifications. Share it with your friends.

More python games,

Leave a Comment

Copy link
Powered by Social Snap