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

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

This is the most popular game we have been playing since our childhood. Whenever we found free time in between our classes or at home we always played this game. It will be fun creating a tic tac toe game on our own. Let’s start developing this fun and popular project.

About Tic Tac Toe Game

This is a very simple game which is played by two people at a time. One player takes O and another X. The player gets turn by turn to mark the space in the 3×3 grid. If the player marks three of their marks diagonally, horizontally and vertically in a row or a column that player is declared the winner.

Python Tic Tac Toe Game project

The main objective of this project is to develop TIC TAC TOE GAME. Pygame is required to start the project. Four modules numpy, pygame, sys, and math are used in this project.

Project Prerequisites

Good knowledge of pygame is required alongwith the knowledge of functions in python. Sound knowledge of the numpy module is also required.

Download Python Tic Tac Toe Game

Please download python tic tac toe game: Tic Tac Toe Game Python Code

Project File Structure

Steps to follow to built Tic Tac Toe Game:

1. Install Pygame
2. Importing Modules
3. Defining Variables and colors
4. Initializing Pygame window
5. Defining functions to create tic tac toe board
6. Function for marking the square and checking the available square
7. Functions for checking for win
8. Rest Code

1. Install Pygame:

Pygame is a set of python modules that are designed for writing video games. You need to install pygame to start developing the project. Write the command given below to install pygame.

Pip install pygame

2. Importing Modules for TIC TAC TOE Python Project:

import numpy as np
import pygame
import math
import sys

Code Explanation:

a. Numpy: It is the fundamental package used for scientific computing in python.
b. math:This module helps in performing mathematical operations on numbers.
c. sys: It provides information about functions, methods and constants of the python interpreter.

3. Defining Variables and colors:

Rows = 3
Columns = 3
sizeofsquare = 200
radiusofcircle = 60
offset = 55
circlelinewidth= 15
xlinewidth = 25
widthofscreen = Columns * sizeofsquare
heightofscreen = Rows * sizeofsquare
colorofline = (0,0,0)
backgroundcolour = (255,255,0)
colorofcircle= (255,105,180)
xcolor = (255,0,0)
player = 0
gameover = False
inmenu = True

Code Explanation:

a. Rows: It is a variable that defines the number of rows.
b. Columns:It is a variable that defines the number of columns.
c. sizeofsquare: This variable contains the size of the tic tac toe game window.
d. radiusofcircle: This variable contains the size of O.
e. circlelinewidth: This variable contains the width of the circle.
f. xlinewidth: This variable contains the width of X.
g. backgroundcolor: This variable stores the background colour.
h. colorofcircle: This variable stores the colour of O.
i. xcolor:This variable stores the colour of X.

4. Initializing Pygame window:

Board = np.zeros((Rows,Columns))
pygame.init()
pygame.display.set_caption("TIC TAC TOE GAME by PythonGeeks")
Screen = pygame.display.set_mode((widthofscreen, heightofscreen))
Screen.fill(backgroundcolour)
drawlines()
pygame.display.update()

Code Explanation:

a. set_caption: This method sets the title of the pygame window.
b. fill(): This method fills the pygame window with the colour that is passed in fill().
c. set_mode(): It closes the previous display.
d. drawlines(): It is a function that draws lines.

5. Defining functions to create tic tac toe board:

def printingboard():
    flippedboard = np.flip(Board, 0)
    print(flippedboard)
    print("")
 
def drawboard():
    drawlines()
    drawfigures()
 
def drawlines():
    pygame.draw.line(Screen, colorofline, (0, 200), (600, 200), 10)
    pygame.draw.line(Screen, colorofline, (0, 400), (600, 400), 10)
    pygame.draw.line(Screen, colorofline, (200, 0), (200, 600), 10)
    pygame.draw.line(Screen, colorofline, (400, 0), (400, 600), 10)
 
def drawfigures():
    for col in range(Columns):
        for row in range(Rows):
            if Board[row][col] == 1:
                pygame.draw.circle(Screen, colorofcircle, (int(col * sizeofsquare + sizeofsquare / 2), int(row * sizeofsquare + sizeofsquare / 2)), radiusofcircle, circlelinewidth)
            elif Board[row][col] == 2:
                pygame.draw.line(Screen, xcolor, (col * sizeofsquare + offset, row * sizeofsquare + offset), (col * sizeofsquare + sizeofsquare - offset, row *sizeofsquare + sizeofsquare - offset), xlinewidth)
                pygame.draw.line(Screen, xcolor, (col * sizeofsquare + offset, row * sizeofsquare + sizeofsquare - offset), (col * sizeofsquare + sizeofsquare - offset, row * sizeofsquare + offset), xlinewidth)
 
def fullboard():
    for col in range(Columns):
        for row in range(Rows):
            if Board[row][col] == 0:
                return False
 
    return True

Code Explanation:

a. printingboard(): This function prints the board on the screen.
b. flip(): It reverses the order of the array.
c. drawboard(): It helps in drawing the board.
d. drawline(): This function draws the line that divides the board into a 3×3 matrix.
e. drawfigures():This function helps in drawing various figures like O,X and line .

6. Function for marking the square and checking the available square:

def availablesquare(row, col):
    is_available = Board[row][col] == 0
    return is_available
 
def marksquare(row, col, player):
    Board[row][col] = player

Code Explanation:

a. availablesquare():This function checks the available square in the tic tac toe board.
b. marksquare():This function marks the square on the tic tac toe board.

7. Functions for checking for win:

def win(player):
    verwin = verticalwin(player)
    horwin = horizontalwin(player)
    diagwin = diagonalwin(player)
 
    if verwin or horwin or diagwin:
        return True
    else:
        return False
 
def verticalwin(player):
    for col in range(Columns):
        if Board[0][col] == player and Board[1][col] == player and Board[2][col] == player:
            drawverticalline(col, player)
            return True
 
    return False
 
def horizontalwin(player):
    for row in range(Rows):
        if Board[row][0] == player and Board[row][1] == player and Board[row][2] == player:
            drawhorizontalline(row, player)
            return True
 
    return False
 
def diagonalwin(player):
    if Board[0][0] == player and Board[1][1] == player and Board[2][2] == player:
        drawdiagonalline(player)
        return True
    elif Board[2][0] == player and Board[1][1] == player and Board[0][2] == player:
        drawdiagonalline(player, False)
        return True
    else:
        return False
 
def drawverticalline(col, player):
    posX = col * sizeofsquare + sizeofsquare / 2
 
    if player == 1:
        pygame.draw.line(Screen, colorofcircle, (posX, 10), (posX, heightofscreen - 10), circlelinewidth)
    else:
        pygame.draw.line(Screen,xcolor, (posX, 10), (posX, heightofscreen - 10), circlelinewidth)
 
def drawhorizontalline(row, player):
    posY = row * sizeofsquare + sizeofsquare/ 2
 
    if player == 1:
        pygame.draw.line(Screen, colorofcircle, (10, posY), (widthofscreen - 10, posY), circlelinewidth)
    else:
        pygame.draw.line(Screen, xcolor, (10, posY), (widthofscreen - 10, posY), circlelinewidth)
 
def drawdiagonalline(player, down_diag=True):
    if down_diag:
        if player == 1:
            pygame.draw.line(Screen, colorofcircle, (25, 25), (widthofscreen - 25, heightofscreen - 25), xlinewidth)
        else:
            pygame.draw.line(Screen, colorofcircle, (25, 25), (widthofscreen - 25, heightofscreen - 25), xlinewidth)
    else:
        if player == 1:
            pygame.draw.line(Screen, colorofcircle, (25, heightofscreen - 25), (widthofscreen - 25, 25), xlinewidth)
        else:
            pygame.draw.line(Screen, xcolor, (25, heightofscreen - 25), (widthofscreen - 25, 25), xlinewidth)

Code Explanation:

a. win(): This function checks the win of the player.
b. verticalwin(): This function checks the vertical win of the player.
c. horizontalwin():This function checks the horizontal win of the player.
d. diagonalwin():This function checks the diagonal win of the player.
e. drawhorizontalline(): It draws a horizontal line if all the three symbols are the same horizontally.
f. drawverticalline():It draws a vertical line if all the three symbols are the same vertically.
g. drawdiagonalline():It draws a line diagonally if all the three symbols are the same diagonally.

8. Rest Code:

while True:
 
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
 
        if event.type == pygame.MOUSEBUTTONDOWN and not gameover:
            positiony = event.pos[1]
            row = int(math.floor(positiony / sizeofsquare))
            positionx = event.pos[0]
            col = int(math.floor(positionx / sizeofsquare))
 
            if player % 2 == 0:
                if availablesquare(row, col):
                    marksquare(row, col, 1)
 
                    if win(1):
                        gameover = True
 
                    player += 1
 
            else:
                if availablesquare(row, col):
                    marksquare(row, col, 2)
 
                    if win(2):
                        gameover = True
 
                    player += 1
 
            if fullboard():
                gameover = True
 
    drawfigures()
    pygame.display.update()

Code Explanation:

a. exit(): It helps to exit the game.
b. update(): It displays surface objects on the monitor.
c. MOUSEBUTTONDOWN: It gets the current state of the mouse device.
d. floor: It returns the floor value of a number.

Python Tic Tac Toe Output

python tic tac toe output

Summary:

We have successfully developed Tic Tac Toe Game in python using pygame module. We also learned various concepts of pygame and python while developing the project.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google | Facebook


Leave a Reply

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