The Classic Tic-Tac-Toe Game in Python 3

Hello There My Gorgeous Friends On The Internet!

So, the best and the most fun way to learn any programming language for me has always been by developing a fun project like a simple game or some project that I would use in my daily life.

So, when I started to learn Python, I started with this No Starch Press published book“Automate The Boring Stuff With Python”which is just awesome and If you are looking for a book to get started learning python, I would recommend you to go through this book. Its very beginner-friendly and it covers almost all the basic topics of python. So, while solving the exercises in this book, I came across this TicTacToe game implementation in python.


What we are going to do?

We are going to build a two-player tic-tac-toe game, which we can play in the command-line. Initially, we’ll make an empty game board and then we’ll take inputs from the players 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.

What will we use?

We will build this game using Python 3, so make sure you have it installed on your laptop/computer and we are good to go.

What we’ll learn?

After building this game, we can get a pretty clear idea about dictionaries in python, how to access dictionaries, how to iterate over dictionaries, for loop, if-else conditions and functions in python.

How does the game work?

The board is numbered like the keyboard’s number pad. And thus, a player can make their move in the game board by entering the number from the keyboard number pad.

Code Time💻

First, let’s see how we are going to use a dictionary to create our game board. A dictionary is a primitive data type in python which stores data in “key: value” format. and thus, we’ll create a dictionary of length 9 and each key will represent a block in the board and its corresponding value will represent the move made by a player. and we’ll create a function printBoard() which we can use every time we want to print the updated board in the game.

theBoard = {'7': ' ' , '8': ' ' , '9': ' ' ,
            '4': ' ' , '5': ' ' , '6': ' ' ,
            '1': ' ' , '2': ' ' , '3': ' ' }
            
def printBoard(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 our game board will look like this:
 | |
-+-+-
 | |
-+-+-
 | |

Now, in the main function, we’ll first take the input from the 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
    
    for i in range(10):
            printBoard(theBoard)
            print("It's your turn," + turn + ".Move to which place?")

            move = input()        

            if theBoard[move] == ' ':
                theBoard[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’

# Now we will check if player X or O has won,for every move after 5 moves. 
        if count >= 5:
            if theBoard['7'] == theBoard['8'] == theBoard['9'] != ' ': # across the top
                printBoard(theBoard)
                print("\nGame Over.\n")                
                print(" **** " +turn + " won. ****")                
                break
            elif theBoard['4'] == theBoard['5'] == theBoard['6'] != ' ': # across the middle
                printBoard(theBoard)
                print("\nGame Over.\n")                
                print(" **** " +turn + " won. ****")
                break
            elif theBoard['1'] == theBoard['2'] == theBoard['3'] != ' ': # across the bottom
                printBoard(theBoard)
                print("\nGame Over.\n")                
                print(" **** " +turn + " won. ****")
                break
            elif theBoard['1'] == theBoard['4'] == theBoard['7'] != ' ': # down the left side
                printBoard(theBoard)
                print("\nGame Over.\n")                
                print(" **** " +turn + " won. ****")
                break
            elif theBoard['2'] == theBoard['5'] == theBoard['8'] != ' ': # down the middle
                printBoard(theBoard)
                print("\nGame Over.\n")                
                print(" **** " +turn + " won. ****")
                break
            elif theBoard['3'] == theBoard['6'] == theBoard['9'] != ' ': # down the right side
                printBoard(theBoard)
                print("\nGame Over.\n")                
                print(" **** " +turn + " won. ****")
                break 
            elif theBoard['7'] == theBoard['5'] == theBoard['3'] != ' ': # diagonal
                printBoard(theBoard)
                print("\nGame Over.\n")                
                print(" **** " +turn + " won. ****")
                break
            elif theBoard['1'] == theBoard['5'] == theBoard['9'] != ' ': # diagonal
                printBoard(theBoard)
                print("\nGame Over.\n")                
                print(" **** " +turn + " won. ****")
                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!!")

        # we have to change the player after every move.
        if turn =='X':
            turn = 'O'
        else:
            turn = 'X' 

And now, we’ll ask the players if they want to play again.

board_keys = []

for key in theBoard:
    board_keys.append(key)
    
restart = input("Do want to play Again?(y/n)")

    if restart == "y" or restart == "Y":  
        for key in board_keys:
            theBoard[key] = " "

        game()    

And boom!! Now we have our game ready.😍😍


Play Time:

 | |
-+-+-
 | |
-+-+-
 | |
It's your turn,X.Move to which place?
7
X| |
-+-+-
 | |
-+-+-
 | |
It's your turn,O.Move to which place?
9
X| |O
-+-+-
 | |
-+-+-
 | |
It's your turn,X.Move to which place?
5
X| |O
-+-+-
 |X|
-+-+-
 | |
It's your turn,O.Move to which place?
3
X| |O
-+-+-
 |X|
-+-+-
 | |O
It's your turn,X.Move to which place?
6
X| |O
-+-+-
 |X|X
-+-+-
 | |O
It's your turn,O.Move to which place?
1
X| |O
-+-+-
 |X|X
-+-+-
O| |O
It's your turn,X.Move to which place?
4
X| |O
-+-+-
X|X|X
-+-+-
O| |O

Game Over.

**** X won. ****

Thanks For Scrolling, Hope you liked it. #HappyCoding👨‍💻