import tkinter as tk
from tkinter import messagebox
# Initialize the main window
root = tk.Tk()
root.title("Tic-Tac-Toe")
root.configure(bg='lightblue') # Set background color
# Variables to store the state of the game
board = [' ' for _ in range(9)]
player = 'X'
scores = {'X': 0, 'O': 0}
# Function to update the button text and board state
def update_board(index, button):
global player
if board[index] == ' ':
board[index] = player
button.config(text=player, fg='blue' if player == 'X' else 'green', bg='white')
if check_win():
messagebox.showinfo("Tic-Tac-Toe", f"Player {player} wins!")
scores[player] += 1
reset_board()
elif ' ' not in board:
messagebox.showinfo("Tic-Tac-Toe", "No winner!")
reset_board()
else:
player = 'O' if player == 'X' else 'X'
# Function to check for a win
def check_win():
win_conditions = [
(0, 1, 2), (3, 4, 5), (6, 7, 8), # Rows
(0, 3, 6), (1, 4, 7), (2, 5, 8), # Columns
(0, 4, 8), (2, 4, 6) # Diagonals
]
for i, j, k in win_conditions:
if board[i] == board[j] == board[k] != ' ':
return True
return False
# Function to reset the board
def reset_board():
global board, player
board = [' ' for _ in range(9)]
player = 'X'
for button in buttons:
button.config(text='', bg='lightgrey')
# Function to show the scores when closing the game
def on_closing():
messagebox.showinfo("Scores", f"Player X: {scores['X']} wins\nPlayer O: {scores['O']} wins")
root.destroy()
# Create buttons for the Tic-Tac-Toe board
buttons = []
for i in range(9):
button = tk.Button(root, text=' ', width=10, height=5, bg='lightgrey',
command=lambda i=i: update_board(i, buttons[i]))
button.grid(row=i//3, column=i%3, padx=5, pady=5) # Add padding for better spacing
buttons.append(button)
# Bind the closing event to the on_closing function
root.protocol("WM_DELETE_WINDOW", on_closing)
# Run the main loop
root.mainloop()
#tikinter | #game | آموزش پایتون