import random
import tkinter as tk
from tkinter import ttk, messagebox

WIN_LINES = (
    (0, 1, 2),
    (3, 4, 5),
    (6, 7, 8),
    (0, 3, 6),
    (1, 4, 7),
    (2, 5, 8),
    (0, 4, 8),
    (2, 4, 6),
)

CELL_BG = "#fafafa"
CELL_X_COLOR = "#1a73e8"
CELL_O_COLOR = "#d93025"
WIN_BG = "#ffe082"


class TicTacToe:
    def __init__(self, root):
        self.root = root
        self.root.title("Крестики-нолики")
        self.root.resizable(False, False)

        self.board = [""] * 9
        self.current = "X"
        self.game_over = False
        self.after_id = None
        self.score_x = 0
        self.score_o = 0
        self.score_d = 0

        self.mode = tk.StringVar(value="two")
        self.active_mode = "two"

        self.score_x_var = tk.StringVar()
        self.score_o_var = tk.StringVar()
        self.score_d_var = tk.StringVar()
        self.status_var = tk.StringVar()

        self.cell_buttons = []

        self.build_ui()
        self.update_score_labels()
        self.new_game()
        self.center_window()

    def build_ui(self):
        main = ttk.Frame(self.root, padding=14)
        main.grid(row=0, column=0, sticky="nsew")

        mode_frame = ttk.LabelFrame(main, text="Режим игры", padding=8)
        mode_frame.grid(row=0, column=0, sticky="ew", pady=(0, 10))
        ttk.Radiobutton(
            mode_frame,
            text="Два игрока",
            value="two",
            variable=self.mode,
            command=self.change_mode,
        ).grid(row=0, column=0, padx=(0, 18))
        ttk.Radiobutton(
            mode_frame,
            text="Против компьютера",
            value="ai",
            variable=self.mode,
            command=self.change_mode,
        ).grid(row=0, column=1)

        score_frame = ttk.Frame(main)
        score_frame.grid(row=1, column=0, sticky="ew", pady=(0, 10))
        for column in range(3):
            score_frame.columnconfigure(column, weight=1)
        ttk.Label(
            score_frame,
            textvariable=self.score_x_var,
            anchor="center",
            font=("Segoe UI", 11, "bold"),
        ).grid(row=0, column=0, sticky="ew")
        ttk.Label(
            score_frame,
            textvariable=self.score_o_var,
            anchor="center",
            font=("Segoe UI", 11, "bold"),
        ).grid(row=0, column=1, sticky="ew")
        ttk.Label(
            score_frame,
            textvariable=self.score_d_var,
            anchor="center",
            font=("Segoe UI", 11, "bold"),
        ).grid(row=0, column=2, sticky="ew")

        board_frame = tk.Frame(main)
        board_frame.grid(row=2, column=0)
        for index in range(9):
            button = tk.Button(
                board_frame,
                text="",
                font=("Segoe UI", 32, "bold"),
                width=3,
                height=1,
                relief="ridge",
                bd=3,
                bg=CELL_BG,
                activebackground="#e8f0fe",
                cursor="hand2",
                command=lambda i=index: self.on_cell(i),
            )
            button.grid(row=index // 3, column=index % 3, padx=2, pady=2)
            self.cell_buttons.append(button)

        ttk.Label(
            main,
            textvariable=self.status_var,
            anchor="center",
            font=("Segoe UI", 12, "bold"),
            width=28,
        ).grid(row=3, column=0, sticky="ew", pady=10)

        controls = ttk.Frame(main)
        controls.grid(row=4, column=0, sticky="ew")
        for column in range(2):
            controls.columnconfigure(column, weight=1)
        ttk.Button(controls, text="Новая игра", command=self.new_game).grid(
            row=0, column=0, sticky="ew", padx=(0, 5)
        )
        ttk.Button(controls, text="Сброс счёта", command=self.reset_scores).grid(
            row=0, column=1, sticky="ew", padx=(5, 0)
        )

    def center_window(self):
        self.root.update_idletasks()
        width = self.root.winfo_width()
        height = self.root.winfo_height()
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        x = (screen_width - width) // 2
        y = max((screen_height - height) // 3, 0)
        self.root.geometry(f"+{x}+{y}")

    def update_score_labels(self):
        self.score_x_var.set(f"X: {self.score_x}")
        self.score_o_var.set(f"O: {self.score_o}")
        self.score_d_var.set(f"Ничьи: {self.score_d}")

    def reset_scores(self):
        try:
            self.score_x = 0
            self.score_o = 0
            self.score_d = 0
            self.update_score_labels()
        except Exception as error:
            messagebox.showerror("Ошибка", str(error))

    def change_mode(self):
        try:
            mode = self.mode.get()
            if mode == self.active_mode:
                return
            self.active_mode = mode
            self.score_x = 0
            self.score_o = 0
            self.score_d = 0
            self.update_score_labels()
            self.new_game()
        except Exception as error:
            messagebox.showerror("Ошибка", str(error))

    def new_game(self):
        try:
            if self.after_id is not None:
                self.root.after_cancel(self.after_id)
                self.after_id = None
            self.board = [""] * 9
            self.current = "X"
            self.game_over = False
            for button in self.cell_buttons:
                button.configure(text="", bg=CELL_BG, fg="black", state="normal")
            self.update_status()
        except Exception as error:
            messagebox.showerror("Ошибка", str(error))

    def update_status(self):
        if self.game_over:
            return
        if self.mode.get() == "ai":
            if self.current == "X":
                self.status_var.set("Ваш ход (X)")
            else:
                self.status_var.set("Ход компьютера (O)")
        else:
            self.status_var.set(f"Ход игрока {self.current}")

    def on_cell(self, index):
        try:
            if self.game_over:
                return
            if self.board[index] != "":
                return
            if self.mode.get() == "ai" and self.current == "O":
                return
            self.make_move(index, self.current)
        except Exception as error:
            messagebox.showerror("Ошибка", str(error))

    def make_move(self, index, player):
        if self.game_over:
            return
        if self.board[index] != "":
            return
        self.board[index] = player
        if player == "X":
            self.cell_buttons[index].configure(text="X", fg=CELL_X_COLOR, bg="#f0f4fa")
        else:
            self.cell_buttons[index].configure(text="O", fg=CELL_O_COLOR, bg="#fbf0ef")

        winner, line = self.find_winner()
        if winner is not None:
            self.game_over = True
            for position in line:
                self.cell_buttons[position].configure(bg=WIN_BG)
            if winner == "X":
                self.score_x += 1
            else:
                self.score_o += 1
            self.update_score_labels()
            if self.mode.get() == "ai":
                if winner == "X":
                    self.status_var.set("Вы победили! (X)")
                else:
                    self.status_var.set("Победил компьютер (O)")
            else:
                self.status_var.set(f"Победил игрок {winner}!")
            return

        if "" not in self.board:
            self.game_over = True
            self.score_d += 1
            self.update_score_labels()
            self.status_var.set("Ничья!")
            return

        self.current = "O" if player == "X" else "X"
        self.update_status()
        if self.mode.get() == "ai" and self.current == "O":
            self.after_id = self.root.after(400, self.computer_move)

    def find_winner(self):
        for line in WIN_LINES:
            first, second, third = line
            value = self.board[first]
            if value != "" and value == self.board[second] == self.board[third]:
                return value, line
        return None, None

    def computer_move(self):
        self.after_id = None
        try:
            if self.game_over:
                return
            if self.mode.get() != "ai":
                return
            if self.current != "O":
                return
            empty_cells = [index for index in range(9) if self.board[index] == ""]
            if not empty_cells:
                return
            best_score = -1000
            best_moves = []
            for index in empty_cells:
                self.board[index] = "O"
                score = self.minimax("X", 0)
                self.board[index] = ""
                if score > best_score:
                    best_score = score
                    best_moves = [index]
                elif score == best_score:
                    best_moves.append(index)
            self.make_move(random.choice(best_moves), "O")
        except Exception as error:
            messagebox.showerror("Ошибка", str(error))

    def minimax(self, player, depth):
        winner, _ = self.find_winner()
        if winner == "O":
            return 10 - depth
        if winner == "X":
            return depth - 10
        if "" not in self.board:
            return 0
        if player == "O":
            best = -1000
            for index in range(9):
                if self.board[index] == "":
                    self.board[index] = "O"
                    score = self.minimax("X", depth + 1)
                    self.board[index] = ""
                    if score > best:
                        best = score
            return best
        best = 1000
        for index in range(9):
            if self.board[index] == "":
                self.board[index] = "X"
                score = self.minimax("O", depth + 1)
                self.board[index] = ""
                if score < best:
                    best = score
        return best


def main():
    root = tk.Tk()

    def handle_exception(exc_type, exc_value, exc_traceback):
        messagebox.showerror("Ошибка", f"{exc_type.__name__}: {exc_value}")

    root.report_callback_exception = handle_exception
    TicTacToe(root)
    root.mainloop()


if __name__ == "__main__":
    try:
        main()
    except Exception as error:
        messagebox.showerror("Критическая ошибка", str(error))