How to Make Tic Tac Toe in Python

Best Tutorial on How to Make Tic Tac Toe in Python!

Do you want to make a two-player Tic Tac Toe game in Python?

Do you don't know how to write code in python, but still want to make a game in it?

ttt



If the answer to any of the above questions is a big yes, then, you have come to the right place!

Today, after reading this article, you will be able to make a Tic Tac Toe game, easily, in Python, even if you do not know how to code! This tutorial will be shown in PyCharm. So, if you want me to give a tutorial on PyCharm, please comment down below or visit our contact us page.

This will be an easy tutorial. After making this application, you can play the game with a friend!
In this tutorial, you will be learning, how you can create a Tic Tac Tow game in python if you do not want to go for any graphics or complexity. This tutorial will be mainly for beginners.

Tic Tac Toe is kind of a classical game, liked by most of the people in the world. So, today, you will learn, how you can make your own Tic Tac Toe rising PyCharm, on your laptop, and enjoy the game with your friends.
Do not worry, the codings will be provided in the last part, but we prefer that you learn how you can make it, and go step by step, and do not do copy paste.

We will do this step by step. Let us start.

How to Make Tic Tac Toe in Python: Step 1

First, create a new file in PyCharm. I am going to name it Tic_Tac_Toe.py. You can name it as you wish. As we will not use any model, we will not be importing anything. This will be a simple game without any graphics, merely for beginners. 
First, we will welcome the players to our game. So, there will be a welcome statement. I will welcome the players by addressing them as, "Welcome to the Tic Tac Toe game - by AllRounders!" You may do this as per your wish. Also, we will be needing the names of the two players, because we won't be looking good calling them players A and B😄 So, here is the code of the first step. Let's view the code, and then we will understand it.


print("Welcome to the Tic Tac Toe game - by AllRounders!")
A = str(input("Player A: "))
B = str(input("Player B: "))

  
Now, let us understand, what these lines of coding mean! As written in the code, the first line prints the statement, Welcome to the Tic Tac Toe game - by AllRounders!, as we mentioned earlier.
I guess most of you know that you being intelligent, that python is an interpreter-based language. It goes line by line and interprets the lines of code and throws an error if required. Also, they do the needful according to the sequence.

So, according to this sequence, first, it will come to the second line where the variable A is mentioned. There, the word str states that all the characters that will be inputted will be considered a string value. This is because the player may enter a name like 123 or so on. If this happens, the program will take it as an integer, and it will create a problem in the game. The function str() saves us from the error. 
After this, the interpreter keeps in mind that it will be a string, and checks the value given in there. It finds the input() function and we get the desired. If you have not known this, the input() function takes input from the user and displays whatever is there between the parenthesis. So, in our case, it will display Player A: and wait for the user to enter an input. The input will be the value that will be assigned to variable A. This is what will happen to the assigning of the variable B.

How to Make Tic Tac Toe in Python: Step 2

In this step, we will create a typical Tic Tac Toe table, and make it such that it can be accessed through a function. Let us first visit the code, and then, we will understand what these lines mean!


def table(a,b,c,d,e,f,g,h,i):
    print(f"{a} | {b} | {c}")
    print("------------")
    print(f"{d} | {e} | {f}")
    print("------------")
    print(f"{g} | {h} | {i}")
    print("------------")

How complex it looks, the lines of code given above are as simple! Now, let us visit these lines for the clearance of your doubts.
But before that, let us see the things used in the section for better understanding:
  • The def command helps us to make a function.
  • The f string helps us to write quick sentences with a mixture of variables (in curly brackets) and text, all in one single section, started and ended with a double quotation mark.
The first line creates a function named table(). Now you would be wondering, why are there so many characters inside the parenthesis of the function? Well, the answer is very simple. These are the parameters, we will have to enter when we will call the function. We will have to write the names, and the in the correct order will be passed to the variable, which again will be printed ahead.
Let us understand it with an example, to make it simpler. Say, I have nine variables, aa, bb, cc, dd, and so on, up to ii. Now, I will call the function. It will be like,
table(aa, bb, cc, dd, ee, ff, gg, hh, ii).
Now what happens is, the value of the variable aa, will be now the value of the parameter a. It will create a variable, within the function, which will be called by the same name, as the parameter. This will be the same for all. Now, if I want, I can replace aa with bb, and then, parameter a will have the value of bb, and parameter b will have the value of aa. I guess it is crystal clear now. 

After the first line, we see some print statements. The ones with -----, are easy to understand. The ones with the f strings are also very simple. The characters under the curly bracket like {a} and {b}, are variable, and their values will be printed, while the rest will be printed as it is.

This is how it will look afterward, according to the value:

table



How to Make Tic Tac Toe in Python: Step 3

Now, we will be creating the game variables and the game loop along with the game function. This step is going to be the stepping stone into the next step. These will be used in the game while playing, and these will decide many things! Now, let us create the function!

def TicTacToe(A, B):
    a = '1'
    b = '2'
    c = '3'
    d = '4'
    e = '5'
    f = '6'
    g = '7'
    h = '8'
    i = '9'
    

Now, what are these? The function TicTactoe() is made and given two arguments; A and B. These are the two names of the two players.
These variables are the same ones we used in the previous step. These are important variables, as they are the nine places in the table of Tic Tac Toe. They are now labeled as the numbers 1-9. When the user will enter the values, these will change to the desired outcome. 
But you will notice that there are two single quotation marks on either side of the number. The reason for that is, the number is not actually a number! It is a character. this means that it contains every letter and number and reads only one character. It will be the same if I wrote '1' and '11'.  It will only be read as 1!
But before we proceed forward, we will be s showing the table to the players. So, the code will be as follows:


table(a,b, c, d, e, f, g, h, i)

The table will be printed. let us move to the next step!


How to Make Tic Tac Toe in Python: Step 4

Now, we will create the main game loop, wherein the players will enter their desired position and play the game. This will decide the game positions. Let us view the code first!


x = 1
    while x <= 9:
        aa = str(input(f"{A}:"))
        if aa == '1' and a == '1':
            a = 'X'
        elif aa == '2' and b == '2':
            b = 'X'
        elif aa == '3' and c == '3':
            c = 'X'
        elif aa == '4' and d == '4':
            d = 'X'
        elif aa == '5' and e == '5':
            e = 'X'
        elif aa == '6' and f == '6':
            f = 'X'
        elif aa == '7' and g == '7':
            g = 'X'
        elif aa == '8' and h == '8':
            h = 'X'
        elif aa == '9' and i == '9':
            i = 'X'
            
        else:
            print("This place is already taken. Better luck next time! You missed this chance!")
            
        x += 1

        table(a,b,c,d,e,f,g,h,i)



        bb = str(input(f"{B}:"))
        if bb == '1' and a == '1':
            a = 'O'
        elif bb == '2' and b == '2':
            b = 'O'
        elif bb == '3' and c == '3':
            c = 'O'
        elif bb == '4' and d == '4':
            d = 'O'
        elif bb == '5' and e == '5':
            e = 'O'
        elif bb == '6' and f == '6':
            f = 'O'
        elif bb == '7' and g == '7':
            g = 'O'
        elif bb == '8' and h == '8':
            h = 'O'
        elif bb == '9' and i == '9':
            i = 'O'

        else:
            print("This place is already taken. Better luck next time! You missed this chance!")

        x += 1

        table(a,b,c,d,e,f,g,h,i)

Now you would be thinking that what this for? The variable x decides that how much time the loop will run.
First, it will ask the first player A to choose a place, according to the number placement of the variable. if he enters 1, it will be converted into a character, and the place is not already taken by another character, it will be converted to X. This will happen the same for B. If the player enters a number already taken, the message is displayed.
Now, you can play the game, but the winner will not be shown. Just, you will have to call the function.


How to Make Tic Tac Toe in Python: Step 5

Now, we will need to take the game to the harder step and give it a final thing. We will need to find out the winner of the round! For that, we will have to make a function. Let us see the code and understand it!

def condition(a, b, c, d, e, f, g, h, i, A, B):
    if a == e == i == 'X':
        exit()
        print(f"The Player A, played by {A} wins.")
    if a == b == c == 'X':
        exit()
        print(f"The Player A, played by {A} wins.")
    if a == d == g == 'X':
        exit()
        print(f"The Player A, played by {A} wins.")
    if b == e == h == 'X':
        exit()
        print(f"The Player A, played by {A} wins.")
    if d == e == f == 'X':
        exit()
        print(f"The Player A, played by {A} wins.")
    if c == e == g == 'X':
        exit()
        print(f"The Player A, played by {A} wins.")
    if c == f == i == 'X':
        exit()
        print(f"The Player A, played by {A} wins.")
    if g == h == i == 'X':
        exit()
        print(f"The Player A, played by {A} wins.")

    else:
        if a == e == i == 'O':
            exit()
            print(f"The Player B, played by {B} wins.")
        if a == b == c == 'O':
            exit()
            print(f"The Player B, played by {B} wins.")
        if a == d == g == 'O':
            exit()
            print(f"The Player B, played by {B} wins.")
        if b == e == h == 'O':
            exit()
            print(f"The Player B, played by {B} wins.")
        if d == e == f == 'O':
            exit()
            print(f"The Player B, played by {B} wins.")
        if c == e == g == 'O':
            exit()
            print(f"The Player B, played by {B} wins.")
        if c == f == i == 'O':
            exit()
            print(f"The Player B, played by {B} wins.")
        if g == h == i == 'O':
            exit()
            print(f"The Player B, played by {B} wins.")
In the code given above, we can easily make out what it means. the interpreter will check whether any of the players are making a set or not, every time they input anything. If it happens, then the winner is announced and the game is exited. If not, it will continue.
Isn't that so simple for such a large amount of code?
Now, we will also be calling it, just after we display the table after the player gives his input of choices. It will be like this:
condition(a,b,c,d,e,f,g,h,i,A,B)



How to Make Tic Tac Toe in Python: Step 6

This is going to be the final step. After you complete this step, your game will be complete! You just have to call the main function like this:
TicTacToe(A, B)


I hope making this game was easy. This is the final code after the development of the code!
print("Welcome to the Tic Tac Toe game - by AllRounders!")
A = str(input("Player A: "))
B = str(input("Player B: "))


def table(a,b,c,d,e,f,g,h,i):
    print(f"{a} | {b} | {c}")
    print("------------")
    print(f"{d} | {e} | {f}")
    print("------------")
    print(f"{g} | {h} | {i}")
    print("------------")

def TicTacToe(A, B):
    a = '1'
    b = '2'
    c = '3'
    d = '4'
    e = '5'
    f = '6'
    g = '7'
    h = '8'
    i = '9'

    table(a,b,c,d,e,f,g,h,i)

    x = 1
    while x <= 9:
        aa = str(input(f"{A}:"))
        if aa == '1' and a == '1':
            a = 'X'
        elif aa == '2' and b == '2':
            b = 'X'
        elif aa == '3' and c == '3':
            c = 'X'
        elif aa == '4' and d == '4':
            d = 'X'
        elif aa == '5' and e == '5':
            e = 'X'
        elif aa == '6' and f == '6':
            f = 'X'
        elif aa == '7' and g == '7':
            g = 'X'
        elif aa == '8' and h == '8':
            h = 'X'
        elif aa == '9' and i == '9':
            i = 'X'

        else:
            print("This place is already taken. Better luck next time! You missed this chance!")

        x += 1

        table(a,b,c,d,e,f,g,h,i)

        condition(a,b,c,d,e,f,g,h,i,A,B)

        print()

        bb = str(input(f"{B}:"))
        if bb == '1' and a == '1':
            a = 'O'
        elif bb == '2' and b == '2':
            b = 'O'
        elif bb == '3' and c == '3':
            c = 'O'
        elif bb == '4' and d == '4':
            d = 'O'
        elif bb == '5' and e == '5':
            e = 'O'
        elif bb == '6' and f == '6':
            f = 'O'
        elif bb == '7' and g == '7':
            g = 'O'
        elif bb == '8' and h == '8':
            h = 'O'
        elif bb == '9' and i == '9':
            i = 'O'

        else:
            print("This place is already taken. Better luck next time! You missed this chance!")

        x += 1

        table(a,b,c,d,e,f,g,h,i)

        condition(a,b,c,d,e,f,g,h,i,A,B)

        print()



def condition(a, b, c, d, e, f, g, h, i, A, B):
    if a == e == i == 'X':
        exit()
        print(f"The Player A, played by {A} wins.")
    if a == b == c == 'X':
        exit()
        print(f"The Player A, played by {A} wins.")
    if a == d == g == 'X':
        exit()
        print(f"The Player A, played by {A} wins.")
    if b == e == h == 'X':
        exit()
        print(f"The Player A, played by {A} wins.")
    if d == e == f == 'X':
        exit()
        print(f"The Player A, played by {A} wins.")
    if c == e == g == 'X':
        exit()
        print(f"The Player A, played by {A} wins.")
    if c == f == i == 'X':
        exit()
        print(f"The Player A, played by {A} wins.")
    if g == h == i == 'X':
        exit()
        print(f"The Player A, played by {A} wins.")

    else:
        if a == e == i == 'O':
            exit()
            print(f"The Player B, played by {B} wins.")
        if a == b == c == 'O':
            exit()
            print(f"The Player B, played by {B} wins.")
        if a == d == g == 'O':
            exit()
            print(f"The Player B, played by {B} wins.")
        if b == e == h == 'O':
            exit()
            print(f"The Player B, played by {B} wins.")
        if d == e == f == 'O':
            exit()
            print(f"The Player B, played by {B} wins.")
        if c == e == g == 'O':
            exit()
            print(f"The Player B, played by {B} wins.")
        if c == f == i == 'O':
            exit()
            print(f"The Player B, played by {B} wins.")
        if g == h == i == 'O':
            exit()
            print(f"The Player B, played by {B} wins.")

TicTacToe(A, B)


Thank you for reading this blog. If you found this blog useful, please let us know. We are always open to feedback. if you have any doubt, you can comment down below, or you can visit our contact us page for more details.

Comments