Python Tic Tac Toe – Create Classic Tic-Tac-Toe Game in Python

FREE Online Courses: Click for Success, Learn for Free - Start Now!

Tic-tac-toe, Xs and Os, or noughts and crosses is one of the most-played game of all time. It is a two-player game consisting of a 3×3 grid which is empty initially and as the game proceeds the grid gets filled by Xs and Os. Once any of its rows vertically or diagonally is filled with the same character, tic tac toe game is finished. Let’s see how can we create this interesting game in Python.

Project Prerequisites

The prerequisites are as follows :

  1. Basic concepts of Python
  2. Tkinter

To install the libraries, you can use pip installer from the cmd/Terminal:

Pip install tkinter

Download Python Tic Tac Toe Code

Please download the code of tic tac toe project: Tic-Tac-Toe Source Code

Let’s code!!

Now, we will develop a python program to create a tic-tac-toe game

Create main.py

Create main.py file and add the following code (alternatively, you can use the code which you downloaded in previous step):

Code:

from tkinter import *

def click(r,c):
    global usr
    global gamestatus
    if(usr=='X' and grd[r][c]==0 and gamestatus==True):
        grd[r][c]='X'
        usr='O'
        curr[r][c].configure(text='X',bg="white")

    if(usr=='O' and grd[r][c]==0 and gamestatus==True):
        grd[r][c]='O'
        usr='X'
        curr[r][c].configure(text='O',bg="gray")
    
    checkWin()

def checkWin():
    global gamestatus
    for i in range(3):
        if grd[0][i]==grd[1][i]==grd[2][i]!=0:
            for j in range(3):
                curr[j][i].config(bg="snow4",fg="white")
            gamestatus=False
    for i in range(3):            
        if grd[i][0]==grd[i][1]==grd[i][2]!=0:
            for j in range(3):
                curr[i][j].config(bg="snow4",fg="white")
            gamestatus=False
    if grd[0][2]==grd[1][1]==grd[2][0]!=0:
            curr[0][2].config(bg="snow4",fg="white")
            curr[1][1].config(bg="snow4",fg="white")
            curr[2][0].config(bg="snow4",fg="white")
            gamestatus=False
    if grd[0][0]==grd[1][1]==grd[2][2]!=0:
            for j in range(3):
                curr[j][j].config(bg="snow4",fg="white")
            gamestatus=False
        
root=Tk()
root.title("ProjectGurukul Tic Tac Toe")

usr="O"
gamestatus=True
grd=[[0,0,0],
     [0,0,0],
     [0,0,0]]

curr=[[0,0,0],
     [0,0,0],
     [0,0,0]]

for i in range(3):
    for j in range(3):
        curr[i][j]=Button(font=('arial',30,'bold'),width=4,
        command=lambda r=i, c=j:click(r,c))
        curr[i][j].grid(row=i,column=j)

mainloop()

Explanation:

After importing tkinter, we will have to perform following tasks:

Define the Following Functions

1. Click(num): It takes the position of the currently clicked cell and checks whether the gamestatus is True or not (i.e the game is over or not) and if the game is not over yet, it checks for the position and then if the corresponding cell is empty it changes its display value.

Finally it calls checkWin function which is explained below.

2. checkWin(): This function updates gamestatus by checking every row, column and diagonal. If every cell of a particular row, column or diagonal is same, gamestatus is set to false indicating game is over now.

So we have discussed the definition of the functions, now we need to look when they should be called and also we need to make a 3×3 grid for GUI.

Define the Following Variables

1. usr: this variable help us to identify the current player (x or o)

2. gamestatus: it is a flag variable which indicates the status of the game ie the game is over or not. Gamestatus= False indicates game is over.

3. curr: It is a list of tkinter buttons which will click() everytime it is clicked.

4. grd: It is a 3×3 matrix which stores the values of all the cells.

Tic Tac Toe Game Output

tic tac toe game

Summary

We have successfully developed python tic tac toe project. This is a simple python project for beginners. We hope you enjoyed the project. Happy Coding!

4 Responses

  1. Abdelrahman Khaled Abdulmuniem Younis says:

    These is a very good project.

  2. TYRE0914 says:

    Thank you!!1

  3. Martin says:

    Thanks for this game. I learnd a lot de-coding it.
    But – coding it myself I got a problem.
    If I’m using grd = [[0]*3]*3 instead of grd=[[0,0,0],[0,0,0],[0,0,0]] or instead of curr = … the problem don’t work properly. But isn’t it the same Code???

    • Gurukul Team says:

      [[0]*3]*3, In this case, python doesn’t create 3 list objects but creates only one and all the indices point to the same object. This is called shallow lists. If you want to try any other way, you can use grd= [[0]*3,[0]*3,[0]*3]. It will work properly. For more understanding execute the following:
      grd=[[0]*3,[0]*3,[0]*3]
      grd=[[0]*3]*3
      grd[1][2]=5
      print(grd)

      Output:[[0, 0, 5], [0, 0, 5], [0, 0, 5]]

Leave a Reply

Your email address will not be published. Required fields are marked *