|
| 1 | +import tkinter as tk |
| 2 | +from tkinter import messagebox |
| 3 | + |
| 4 | +class TicTacToe: |
| 5 | + def __init__(self): |
| 6 | + # Create the main window |
| 7 | + self.window = tk.Tk() |
| 8 | + self.window.title("Tic Tac Toe - Python GUI") |
| 9 | + |
| 10 | + # X always starts |
| 11 | + self.turn = "X" |
| 12 | + self.buttons = [] |
| 13 | + self.game_over = False |
| 14 | + |
| 15 | + # Create a 3x3 Grid of Buttons |
| 16 | + for i in range(3): |
| 17 | + row = [] |
| 18 | + for j in range(3): |
| 19 | + # Create a single button |
| 20 | + btn = tk.Button(self.window, text="", font=("Arial", 20), width=5, height=2, |
| 21 | + command=lambda x=i, y=j: self.on_click(x, y)) |
| 22 | + # Place it on the grid |
| 23 | + btn.grid(row=i, column=j) |
| 24 | + row.append(btn) |
| 25 | + self.buttons.append(row) |
| 26 | + |
| 27 | + # Start the application loop |
| 28 | + self.window.mainloop() |
| 29 | + |
| 30 | + def on_click(self, row, col): |
| 31 | + # If the button is already clicked or game is over, do nothing |
| 32 | + if self.game_over or self.buttons[row][col]["text"] != "": |
| 33 | + return |
| 34 | + |
| 35 | + # Set the button text to X or O |
| 36 | + self.buttons[row][col]["text"] = self.turn |
| 37 | + |
| 38 | + # Check if someone won |
| 39 | + if self.check_winner(): |
| 40 | + messagebox.showinfo("Game Over", f"Player {self.turn} wins!") |
| 41 | + self.game_over = True |
| 42 | + elif self.check_draw(): |
| 43 | + messagebox.showinfo("Game Over", "It's a Draw!") |
| 44 | + self.game_over = True |
| 45 | + else: |
| 46 | + # Switch turns |
| 47 | + self.turn = "O" if self.turn == "X" else "X" |
| 48 | + |
| 49 | + def check_winner(self): |
| 50 | + # Check all rows, columns, and diagonals for a match |
| 51 | + for i in range(3): |
| 52 | + if self.buttons[i][0]["text"] == self.buttons[i][1]["text"] == self.buttons[i][2]["text"] != "": |
| 53 | + return True |
| 54 | + if self.buttons[0][i]["text"] == self.buttons[1][i]["text"] == self.buttons[2][i]["text"] != "": |
| 55 | + return True |
| 56 | + |
| 57 | + # Diagonals |
| 58 | + if self.buttons[0][0]["text"] == self.buttons[1][1]["text"] == self.buttons[2][2]["text"] != "": |
| 59 | + return True |
| 60 | + if self.buttons[0][2]["text"] == self.buttons[1][1]["text"] == self.buttons[2][0]["text"] != "": |
| 61 | + return True |
| 62 | + |
| 63 | + return False |
| 64 | + |
| 65 | + def check_draw(self): |
| 66 | + for row in self.buttons: |
| 67 | + for btn in row: |
| 68 | + if btn["text"] == "": |
| 69 | + return False |
| 70 | + return True |
| 71 | + |
| 72 | +if __name__ == "__main__": |
| 73 | + game = TicTacToe() |
0 commit comments