import tkinter as tk
from tkinter import messagebox
def check_winner():
"""Checks if there is a winner or if the game is a draw."""
for row in board:
if row[0]["text"] == row[1]["text"] == row[2]["text"] != "":
return row[0]["text"]
for col in range(3):
if board[0][col]["text"] == board[1][col]["text"] == board[2][col]["text"] != "":
return board[0][col]["text"]
if board[0][0]["text"] == board[1][1]["text"] == board[2][2]["text"] != "":
return board[0][0]["text"]
if board[0][2]["text"] == board[1][1]["text"] == board[2][0]["text"] != "":
return board[0][2]["text"]
if all(board[row][col]["text"] != "" for row in range(3) for col in range(3)):
return "Draw"
return None
def on_click(row, col):
"""Handles button click events."""
global current_player
if board[row][col]["text"] == "":
board[row][col]["text"] = current_player
winner = check_winner()
if winner:
if winner == "Draw":
messagebox.showinfo("Game Over", "It's a draw!")
else:
messagebox.showinfo("Game Over", f"Player {winner} wins!")
reset_board()
else:
current_player = "O" if current_player == "X" else "X"
def reset_board():
"""Resets the game board for a new game."""
global current_player
current_player = "X"
for row in range(3):
for col in range(3):
board[row][col]["text"] = ""
# Create the main window
root = tk.Tk()
root.title("Tic-Tac-Toe")
# Initialize variables
current_player = "X"
board = [[None for _ in range(3)] for _ in range(3)]
# Create the game board (3x3 buttons)
for row in range(3):
for col in range(3):
button = tk.Button(
root, text="", font=("Helvetica", 20), height=2, width=5,
command=lambda r=row, c=col: on_click(r, c)
)
button.grid(row=row, column=col)
board[row][col] = button
# Run the application
root.mainloop()
0 Comments:
Post a Comment