TicTacToe Game App with Python Code

Gopathi Suresh Kumar
2 min readApr 8, 2023

“Hey everyone, I’m excited to share my latest project with you — a Tic-Tac-Toe game with a graphical user interface! 🎮🖥️

I created this game using Python and the tkinter module, which allowed me to create a GUI that lets players click on the board to make moves and see the state of the game in real-time. It’s a fun and interactive way to play Tic-Tac-Toe and see who can get three in a row first!

To create the game, I defined a TicTacToeApp class that initializes the GUI and creates the buttons for the board. I also wrote methods to handle button clicks, check if the current player has won the game, and switch between players.

You can check out the full implementation on my Jupyter Notebook and even try playing the game yourself! It’s a great way to learn more about Python programming and GUI development.

If you’re interested in game development, Python programming, or graphical user interfaces, this project is a great way to learn more and get hands-on experience. Give it a try and let me know what you think! #PythonProgramming #TicTacToe #GraphicalUserInterface #GameDevelopment”

Python Code

import tkinter as tk

class TicTacToeApp:
def __init__(self):
self.board = [“ “, “ “, “ “, “ “, “ “, “ “, “ “, “ “, “ “]
self.current_player = “X”

self.root = tk.Tk()
self.root.title(“Tic-Tac-Toe”)

# create the buttons for the board
self.buttons = []
for i in range(9):
button = tk.Button(self.root, text=” “, width=5, height=2,
command=lambda i=i: self.button_click(i))
button.grid(row=i//3, column=i%3)
self.buttons.append(button)

# create a label to display the current player
self.status_label = tk.Label(self.root, text=”Player “ + self.current_player + “‘s turn”)
self.status_label.grid(row=3, column=0, columnspan=3)

self.root.mainloop()

def button_click(self, index):
“””Handles a button click on the board.”””
if self.board[index] == “ “:
self.board[index] = self.current_player
self.buttons[index].config(text=self.current_player)

if self.check_win():
self.status_label.config(text=”Player “ + self.current_player + “ wins!”)
for button in self.buttons:
button.config(state=”disabled”)
elif “ “ not in self.board:
self.status_label.config(text=”Tie game!”)
else:
self.switch_player()
self.status_label.config(text=”Player “ + self.current_player + “‘s turn”)

def check_win(self):
“””Checks if the current player has won the game.”””
win_conditions = [[0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6]]
for condition in win_conditions:
if self.board[condition[0]] == self.current_player and \
self.board[condition[1]] == self.current_player and \
self.board[condition[2]] == self.current_player:
return True
return False

def switch_player(self):
“””Switches the current player.”””
if self.current_player == “X”:
self.current_player = “O”
else:
self.current_player = “X”

app = TicTacToeApp()

--

--