Build Tic Tac Toe Game using Python Code with the Help of ChatGPT

276

In this tutorial, I’ll try to provide you with how to get help from ChatGPT and code the Game. Try this source Code.

import tkinter as tk
from tkinter import messagebox
def check_winner():
    for combo in winning_combinations:
        a, b, c = combo
        if board[a] == board[b] == board[c] != “”:
            return board[a]
    return None
def check_draw():
    return “” not in board
def handle_click(index):
    global current_player
    global winner
    if board[index] == “” and not winner:
        board[index] = current_player
        buttons[index].config(text=current_player, state=tk.DISABLED)
        current_player = “X” if current_player == “O” else “O”
        winner = check_winner()
        if winner:
            messagebox.showinfo(“Tic Tac Toe”, f”Player {winner} wins!”)
            reset_game()
        elif check_draw():
            messagebox.showinfo(“Tic Tac Toe”, “It’s a draw!”)
            reset_game()
def reset_game():
    global board, current_player, winner
    board = [“”] * 9
    current_player = “X”
    winner = None
    for button in buttons:
        button.config(text=””, state=tk.NORMAL)
def exit_game():
    root.destroy()
winning_combinations = [(0, 1, 2), (3, 4, 5), (6, 7, 8),
                        (0, 3, 6), (1, 4, 7), (2, 5, 8),
                        (0, 4, 8), (2, 4, 6)]
root = tk.Tk()
root.title(“Tic Tac Toe”)
# Dark mode colors
bg_color = “#333”
text_color = “white”
font_size = 16
root.configure(bg=bg_color)
board = [“”] * 9
current_player = “X”
winner = None
buttons = [tk.Button(root, text=””, width=10, height=3, command=lambda i=i: handle_click(i), bg=bg_color, fg=text_color, font=(“Arial”, font_size)) for i in range(9)]
for i, button in enumerate(buttons):
    row = i // 3
    col = i % 3
    button.grid(row=row, column=col)
reset_button = tk.Button(root, text=”Reset”, command=reset_game, bg=bg_color, fg=text_color, font=(“Arial”, font_size))
reset_button.grid(row=3, column=0, columnspan=2)
exit_button = tk.Button(root, text=”Exit”, command=exit_game, bg=bg_color, fg=text_color, font=(“Arial”, font_size))
exit_button.grid(row=3, column=2, columnspan=2)
root.mainloop()