How to create Tic Tac Toe Game in Python | Game in Python | Source Code

Hello friends how are you, Today in this blog post "Tic Tac Toe Game in Python" I am going to teach you how you can create Tic Tac Toe Game in Python using very simple lines of code. If you are a computer science students then this post will help you definitely just go through this post to get complete knowledge.

Now  i am going to explain it step by step so just go through this post to understand this completely.

If you want to understand this through video then watch this video i have explained it step by step live


Step 1: Install Python : Click here to watch a video on how to install python or Open any browser and type Download Python and click the first link you will get official website of python here you will get a Download button and after clicking on this button you will get exe of latest python version just install it into your system. 

Step 2: Install Pycharm | Create Project | Install LibraryClick here to watch a single video on How to install Pycharm | Create Project | Install Library  or To install Pycharm IDE Open any browser and type Download Pycharm and click the first link you will get official website of Pycharm  here you will get a black download button and after clicking on this button you will get an exe of Pycharm , just install it into your system. If you are facing problem to install then watch the above video i have explained step by step.

Learn Python:Want to learn complete python for free click here 

Step 3: Create Project : Open Pycharm  click on File which is in top left of screen and select New Project. Then you will get a screen. Here first you need to select directory of your project and then type a name for your project like "TicTacGame" after directory name, and at last click the create button to create this project. 

Step 4: Create Python file: To create a python file for coding in your project just right click on project name "TicTacGame" and select new and click on Python File , you will get popup screen in which you have to type a name like "Program" for python file and press enter, it will create a python file with name Program.py inside the project TicTacGame. 

Step 5: Code ExplanationTo explain the code i have divided it into six part and now i am going to explain each part one by one

Import Library: Here i have imported the needed library to create this game

#import needed library
from tkinter import *
import random as r

Here to create this project i have used two libraries tkinter and random.

Create Button for Cell: As we know that in the Tic Tac Game there are nine cell and i have placed a button in each cell using a function.

#Function to define a button
def CellButton(frame):
    b=Button(frame,padx=1,bg="#27386B",width=3,text="   ",font=('algerian',60,'normal'),relief="sunken",bd=5)
    return b

Here CellButton is a function and it is taking a single parameter. In the above code i have set many property in button like padding, font style, background color etc to make this button interesting. Text of button is empty to make game board clear.

Change Letter: In this game there are two Letters ['X','O'] are used, In this step we will change the current letter after button click for the next player

#changing operator for the next player
def changeLetter():
    global a
    for i in ['O','X']:
        if not(i==a):
            a=i
            break

Here changeLetter() is function that will work like an Inverter. If the current letter is X then it will set O as a next letter and Voce-Versa.

Reset Game Board: After getting the result of current game we will reset the game board.

#Reset the gameboard
def resetBoard():
    global a
    for i in range(3):
        for j in range(3):
                board[i][j]["text"]=" "
                board[i][j]["state"]=NORMAL
    a=r.choice(['O','X'])

Here resetBoard is a function that will reset the game board by replacing each button text with space.

Check Win: There are eight possible condition for winning this game for a player, In this step we will check all these possible condition on every click of players. If the condition is satisfied then we will show the result and reset the game board.

#check for winning
def checkWinning():
    for i in range(3):
            if(board[i][0]["text"]==board[i][1]["text"]==board[i][2]["text"]==a or board[0][i]["text"]==board[1][i]["text"]==board[2][i]["text"]==a):
                if a == 'X':
                    lblMesage.config(text="'" + firstPlayer.get() + "' is Winner")
                else:
                    lblMesage.config(text="'" + secondPlayer.get() + "' is Winner")
                resetBoard()
    if(board[0][0]["text"]==board[1][1]["text"]==board[2][2]["text"]==a or board[0][2]["text"]==board[1][1]["text"]==board[2][0]["text"]==a):
        if a =='X':
         lblMesage.config(text="'"+firstPlayer.get()+"' is Winner")
        else:
            lblMesage.config(text="'" + secondPlayer.get() + "' is Winner")
        resetBoard()
    elif(board[0][0]["state"]==board[0][1]["state"]==board[0][2]["state"]==board[1][0]["state"]==board[1][1]["state"]==board[1][2]["state"]==board[2][0]["state"]==board[2][1]["state"]==board[2][2]["state"]==DISABLED):
        lblMesage.config(text="The match is Tied!")
        resetBoard()

Here  checkWinning is a function that will check all possible condition and show the result if condition satisfies and after that it will reset the game board using resetBoard function.

Click Button: This is the main activity of this project. Here first we will set the current Letter in clicked cell and then we will check the winning condition. If condition satisfies then we will  show the result otherwise will change the current letter for next player.

def click(row,col):
        board[row][col].config(text=a,state=DISABLED,disabledforeground=colour[a])
        lblMesage.config(text="")
        checkWinning()
        changeLetter()
        if a=='X':
         label.config(text=firstPlayer.get()+"'s Chance")
        else:
         label.config(text=secondPlayer.get() + "'s Chance")

Here click is a function that takes the current cell position to set the current letter to it and then it will perform winning operation and at last it will change the current letter for next player.

Design Game Board: Here in this step we will design an attractive board for our game.

#Defining window
root=Tk()
#Setting title for window
root.title("Krazy:Tic-Tac-Toe Game")
#setting width and height for game window
root.geometry("800x490")
#setting background color
root["bg"]="#03151C"
#declaring variables
firstPlayer=StringVar()
secondPlayer=StringVar()
#label for first player
Label(root,text="First Player Name[X]",bg="#03151C",fg="white",font=("Arial",15,"bold")).place(x=550,y=20)
#textbox for first player
Entry(root,font=("Arial",15,"bold"),textvariable=firstPlayer).place(x=550,y=55)
#label for second player
Label(root,text="Second Player Name[O]",bg="#03151C",fg="white",font=("Arial",15,"bold")).place(x=550,y=90)
#textbox for second player
Entry(root,font=("Arial",15,"bold"),textvariable=secondPlayer).place(x=550,y=125)
#label for displaying game result
lblMesage=Label(root,bg="#03151C",fg="yellow",font=("Arial",15,"bold"))
lblMesage.place(x=550,y=185)
#Defining Two operators
a=r.choice(['O','X'])
#setting color for operators
colour={'O':"yellow",'X':"white"}
#variable for creating board
board=[[],[],[]]
for i in range(3):
        for j in range(3):
                board[i].append(CellButton(root))
                board[i][j].config(command= lambda row=i,col=j:click(row,col))
                board[i][j].grid(row=i,column=j)
#label for displaying player's turn
label=Label(text="Welcome",font=('arial',15,'bold'),bg="#03151C",fg="white")
label.place(x=550,y=450)
#run Application
root.mainloop()

Here in the above code i have explained each line of code using comment so i think there is need to describe it again.

Step 6: Complete CodeHere is the complete code for this project/program

"""
Krazyprogrammer Presents Tic Tac Toe Game
"""
#import needed library
from tkinter import *
import random as r
#Function to define a button
def CellButton(frame):
    b=Button(frame,padx=1,bg="#27386B",width=3,text="   ",font=('algerian',60,'bold'),relief="sunken",bd=5)
    return b
#changing operator for the next player
def changeLetter():
    global a
    for i in ['O','X']:
        if not(i==a):
            a=i
            break
#Reset the gameboard
def resetBoard():
    global a
    for i in range(3):
        for j in range(3):
                board[i][j]["text"]=" "
                board[i][j]["state"]=NORMAL
    a=r.choice(['O','X'])
#check for winning
def checkWinning():
    for i in range(3):
            if(board[i][0]["text"]==board[i][1]["text"]==board[i][2]["text"]==a or board[0][i]["text"]==board[1][i]["text"]==board[2][i]["text"]==a):
                if a == 'X':
                    lblMesage.config(text="'" + firstPlayer.get() + "' is Winner")
                else:
                    lblMesage.config(text="'" + secondPlayer.get() + "' is Winner")
                resetBoard()
    if(board[0][0]["text"]==board[1][1]["text"]==board[2][2]["text"]==a or board[0][2]["text"]==board[1][1]["text"]==board[2][0]["text"]==a):
        if a =='X':
         lblMesage.config(text="'"+firstPlayer.get()+"' is Winner")
        else:
            lblMesage.config(text="'" + secondPlayer.get() + "' is Winner")
        resetBoard()
    elif(board[0][0]["state"]==board[0][1]["state"]==board[0][2]["state"]==board[1][0]["state"]==board[1][1]["state"]==board[1][2]["state"]==board[2][0]["state"]==board[2][1]["state"]==board[2][2]["state"]==DISABLED):
        lblMesage.config(text="The match is Tied!")
        resetBoard()

def click(row,col):
        board[row][col].config(text=a,state=DISABLED,disabledforeground=colour[a])
        lblMesage.config(text="")
        checkWinning()
        changeLetter()
        if a=='X':
         label.config(text=firstPlayer.get()+"'s Chance")
        else:
         label.config(text=secondPlayer.get() + "'s Chance")

#Defining window
root=Tk()
#Setting title for window
root.title("Krazy:Tic-Tac-Toe Game")
#setting width and height for game window
root.geometry("800x490")
#setting background color
root["bg"]="#03151C"
#declaring variables
firstPlayer=StringVar()
secondPlayer=StringVar()
#label for first player
Label(root,text="First Player Name[X]",bg="#03151C",fg="white",font=("Arial",15,"bold")).place(x=550,y=20)
#textbox for first player
Entry(root,font=("Arial",15,"bold"),textvariable=firstPlayer).place(x=550,y=55)
#label for second player
Label(root,text="Second Player Name[O]",bg="#03151C",fg="white",font=("Arial",15,"bold")).place(x=550,y=90)
#textbox for second player
Entry(root,font=("Arial",15,"bold"),textvariable=secondPlayer).place(x=550,y=125)
#label for displaying game result
lblMesage=Label(root,bg="#03151C",fg="yellow",font=("Arial",15,"bold"))
lblMesage.place(x=550,y=185)
#Defining Two operators
a=r.choice(['O','X'])
#setting color for operators
colour={'O':"yellow",'X':"white"}
#variable for creating board
board=[[],[],[]]
for i in range(3):
        for j in range(3):
                board[i].append(CellButton(root))
                board[i][j].config(command= lambda row=i,col=j:click(row,col))
                board[i][j].grid(row=i,column=j)
#label for displaying player's turn
label=Label(text="Welcome",font=('arial',15,'bold'),bg="#03151C",fg="white")
label.place(x=550,y=450)
#run Application
root.mainloop()

Open your python file program.py then type this code or you can copy this code from here for your personal use only.
Step 7: Run Code: To run this code just right click on coding area and click on Run Program and you will get a output screen like below.

Tic Tac Toe Game in Python

This is the dashboard of this game here you first need to type the name of first player and second player for example see the below screenshot
Tic Tac Toe Game in Python

Here in this game i am using Letter X for first player and Letter O for second player i.e the Letter for Ankita is X and Ruchi is O. After doing this just click on game board cell and play.
Winning Screenshot:
Tic Tac Toe Game in Python

Here in the above screenshot you can see that Letter X satisfies the winning condition so Game is displaying Ankita as a Winner.

Tied Screenshot: 
Tic Tac Toe Game in Python

In the above screenshot is no remaining cell block to click and  no winning condition satisfies so the match is Tied.

I hope now you can  create "Tic Tac Toe Game in Python ". If you have any doubt regarding this post  or you want something more in this post then let me know by comment below i will work on it definitely.
 

Request:-If you found this post helpful then let me know by your comment and share it with your friend. 
 
If you want to ask a question or want to suggest then type your question or suggestion in comment box so that we could do something new for you all. 

If you have not subscribed my website then please subscribe my website. Try to learn something new and teach something new to other. 

If you like my post then share it with your friends. Thanks­čśŐHappy Coding.

Post a Comment

0 Comments