17.Tic-Tac-Toe.py
import tkinter as tk
from tkinter import messagebox
# Initialize current player as "X" and set winner flag to False
current_player = "X"
winner = False
# Function to check for a winner
def who_wins():
global winner
# List of winning combinations
for combo in [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]:
# Check if the buttons in the current combination have the same text and are not empty
if buttons[combo[0]]["text"] == buttons[combo[1]]["text"] == buttons[combo[2]]["text"] != " ":
# Highlight the winning combination with a green background
buttons[combo[0]].config(bg="green")
buttons[combo[1]].config(bg="green")
buttons[combo[2]].config(bg="green")
# Show a message box declaring the winner
messagebox.showinfo("Tic-Tac-Toe", f"Player {buttons[combo[0]]['text']} wins!")
# Set winner flag to True
winner = True
return
# Check for a tie
if all(button["text"] != " " for button in buttons) and not winner:
# Show a message box declaring a tie
messagebox.showinfo("Tic-Tac-Toe", "It's a tie!")
buttons[combo[0]].config(bg="red")
buttons[combo[1]].config(bg="red")
buttons[combo[2]].config(bg="red")
buttons[combo[3]].config(bg="red")
buttons[combo[4]].config(bg="red")
buttons[combo[5]].config(bg="red")
buttons[combo[6]].config(bg="red")
buttons[combo[7]].config(bg="red")
buttons[combo[8]].config(bg="red")
# Set winner flag to True
winner = True
# Function to handle button clicks
def button_click(index):
# Check if the button is empty and the game is not over
if buttons[index]["text"] == " " and not winner:
# Set the button's text to the current player's symbol
buttons[index]["text"] = current_player
# Check for a winner after the current move
who_wins()
# Switch to the other player's turn
toggle_player()
# Function to toggle between players
def toggle_player():
global current_player
# Switch between "X" and "O"
current_player = "X" if current_player == "O" else "O"
# Update the label to show whose turn it is
label.config(text=f"Player {current_player}'s turn")
# Create the main window
root = tk.Tk()
# Set the title of the window
root.title("Tic-Tac-Toe")
# Create buttons for the game board
buttons = [tk.Button(root, text=" ", font=("normal", 30), width=5, height=2, command=lambda i=i: button_click(i)) for i in range(9)]
# Place the buttons in a 3x3 grid layout
for i, button in enumerate(buttons):
button.grid(row=i // 3, column=i % 3)
# Create a label to display whose turn it is
label = tk.Label(root, text=f"Player {current_player}'s turn", font=("normal", 15))
# Place the label below the game board
label.grid(row=3, column=0, columnspan=3)
# Start the tkinter event loop
root.mainloop()
Comments
Post a Comment