A Simple Python Tic-Tac-Toe Game Using Pygame

Creating A Python Tic-Tac-Toe Game Using Pygame

Hello guys, welcome back to the Pygame Series, today we are going to build another simple but cool game. Today I am going to show you how you can build a Python. But, moving far let me give you the definition of the Tic Tac Toe Game.

Tic Tac Toe Pygame

Definition of Tic Tac Toe Game: It is a traditional strategy game where two players look for different turns to complete a row, a column, or a diagonal with either three O’s or three X’s drawn in the spaces of a grid of nine squares. The squares contain different noughts and crosses. It is typically a paper-and-pencil game but now programmed like a computer game. The player whoever first completes placing three of their marks in a horizontal, vertical, or diagonal row in a square wins.

Now, as we have completed the first step. Let us move on directly on how to create a Python Tic Tac Toe Game using Pygame.

Requirements for the Game:

  • A good & fast processing PC with a Python environment & pygame package installed. You can choose Mac Book, Asus Zenbook, Dell Inspiron, or any Pc with a high processor.
  • Code Ide or Code Editor.
  • A notebook for writing important notation.
  • Your Focus.

Working of our Pygame:

Our Tic Tac Toe is programmed in other to allow two users or players to play the game in the same time. It’s GUI game & gives an instant alert when players wins or losses or draw the game.

Steps to build a Tic Tac Toe Game:

  • First of all, create a folder named any in your PC & drag it to your code editor.
  • Secondly, open your command prompt(CMD) & install the Pygame package by typing Pip install Pygame command.
  • Thirdly, make a file called main.py & folders called image. It will you to store all your codes & image resource files needed for the game.
  • Set your codes which are given below to your respective files. You can download the image file this is given in the button link.
  • Lastly, run your Pygame by typing Python main.py in your Command. That’s it you have your game.


import pygame
import math
# Initializing Pygame
pygame.init() # Screen
WIDTH = 300
ROWS = 3
win = pygame.display.set_mode((WIDTH, WIDTH))
pygame.display.set_caption("TicTacToe") # Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (200, 200, 200)
RED = (255, 0, 0)
BLUE = (0, 0, 255) # Images
X_IMAGE = pygame.transform.scale(pygame.image.load("images/x.png"), (80, 80))
O_IMAGE = pygame.transform.scale(pygame.image.load("images/o.png"), (80, 80)) # Fonts
END_FONT = pygame.font.SysFont('courier', 40) def draw_grid(): gap = WIDTH // ROWS # Starting points x = 0 y = 0 for i in range(ROWS): x = i * gap pygame.draw.line(win, GRAY, (x, 0), (x, WIDTH), 3) pygame.draw.line(win, GRAY, (0, x), (WIDTH, x), 3) def initialize_grid(): dis_to_cen = WIDTH // ROWS // 2 # Initializing the array game_array = [[None, None, None], [None, None, None], [None, None, None]] for i in range(len(game_array)): for j in range(len(game_array[i])): x = dis_to_cen * (2 * j + 1) y = dis_to_cen * (2 * i + 1) # Adding centre coordinates game_array[i][j] = (x, y, "", True) return game_array def click(game_array): global x_turn, o_turn, images # Mouse position m_x, m_y = pygame.mouse.get_pos() for i in range(len(game_array)): for j in range(len(game_array[i])): x, y, char, can_play = game_array[i][j] # Distance between mouse and the centre of the square dis = math.sqrt((x - m_x) ** 2 + (y - m_y) ** 2) # If it's inside the square if dis < WIDTH // ROWS // 2 and can_play: if x_turn: # If it is X's turn images.append((x, y, X_IMAGE)) x_turn = False o_turn = True game_array[i][j] = (x, y, 'x', False) elif o_turn: # If it is O's turn images.append((x, y, O_IMAGE)) x_turn = True o_turn = False game_array[i][j] = (x, y, 'o', False) # Checking if someone has won
def has_won(game_array): # Checking rows for row in range(len(game_array)): if (game_array[0][2] == game_array[1][2] == game_array[2][2]) and game_array[0][2] != "": display_message(game_array[0][2].upper() + " has won!") return True # Checking columns for col in range(len(game_array)): if (game_array[0][2] == game_array[1][2] == game_array[2][2]) and game_array[0][2] != "": display_message(game_array[0][2].upper() + " has won!") return True # Checking main diagonal if (game_array[0][0][2] == game_array[1][1][2] == game_array[2][2][2]) and game_array[0][0][2] != "": display_message(game_array[0][0][2].upper() + " has won!") return True # Checking reverse diagonal if (game_array[0][2][2] == game_array[1][1][2] == game_array[2][0][2]) and game_array[0][2][2] != "": display_message(game_array[0][2][2].upper() + " has won!") return True return False def has_drawn(game_array): for i in range(len(game_array)): for j in range(len(game_array[i])): if game_array[i][j][2] == "": return False display_message("It's a draw!") return True def display_message(content): pygame.time.delay(500) win.fill(WHITE) end_text = END_FONT.render(content, 1, BLACK) win.blit(end_text, ((WIDTH - end_text.get_width()) // 2, (WIDTH - end_text.get_height()) // 2)) pygame.display.update() pygame.time.delay(3000) def render(): win.fill(WHITE) draw_grid() # Drawing X's and O's for image in images: x, y, IMAGE = image win.blit(IMAGE, (x - IMAGE.get_width() // 2, y - IMAGE.get_height() // 2)) pygame.display.update() def main(): global x_turn, o_turn, images, draw images = [] draw = False run = True x_turn = True o_turn = False game_array = initialize_grid() while run: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() if event.type == pygame.MOUSEBUTTONDOWN: click(game_array) render() if has_won(game_array) or has_drawn(game_array): run = False while True: if __name__ == '__main__': main()


It is simple beginner friendly Tic-Tac-Toe Game which is easy for any beginners to built & understand. So, enjoy building & playing the game. Also, it’s important to follow the steps to avoid any error, if any arises you can comment below or mail us. Lastly, if you find useful please share it. Thank You.

Source: https://thecodezine.com/a-simple-python-tic-tac-toe-game-using-pygame/

You might also like this video