0% found this document useful (0 votes)
2 views3 pages

Tic Tac Toe

Tic tac Toe game through python

Uploaded by

madhan000183
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

Tic Tac Toe

Tic tac Toe game through python

Uploaded by

madhan000183
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

import tkinter as tk

from tkinter import messagebox

class TicTacToeApp:

def __init__(self, root):

self.root = root

self.root.title("Tic-Tac-Toe")

self.current_player = "X"

self.buttons = [[None for _ in range(3)] for _ in range(3)]

self.create_widgets()

def create_widgets(self):

for row in range(3):

for col in range(3):

button = tk.Button(self.root, text="", font=('Arial', 25), width=3,


height=1, background="light blue",

command=lambda r=row, c=col:


self.on_button_click(r, c))

button.grid(row=row, column=col, padx=5, pady=5)

self.buttons[row][col] = button

def on_button_click(self, row, col):

button = self.buttons[row][col]

if button["text"] == "":

button["text"] = self.current_player
if self.check_winner():

messagebox.showinfo("Game Over", f"Player {self.current_player}


wins hurray !")

self.reset_game()

elif self.check_draw():

messagebox.showinfo("Game Over", "It's a draw! better luck next


time!")

self.reset_game()

else:

self.current_player = "O" if self.current_player == "X" else "X"

def check_winner(self):

for row in range(3):

if self.buttons[row][0]["text"] == self.buttons[row][1]["text"] ==
self.buttons[row][2]["text"] != "":

return True

for col in range(3):

if self.buttons[0][col]["text"] == self.buttons[1][col]["text"] ==
self.buttons[2][col]["text"] != "":

return True

if self.buttons[0][0]["text"] == self.buttons[1][1]["text"] ==
self.buttons[2][2]["text"] != "":

return True

if self.buttons[0][2]["text"] == self.buttons[1][1]["text"] ==
self.buttons[2][0]["text"] != "":

return True

return False

def check_draw(self):
for row in range(3):

for col in range(3):

if self.buttons[row][col]["text"] == "":

return False

return True

def reset_game(self):

for row in range(3):

for col in range(3):

self.buttons[row][col]["text"] = ""

self.current_player = "X"

if __name__ == "__main__":

root = tk.Tk()

app = TicTacToeApp(root)

root.mainloop()

You might also like