import random
import tkinter as tk
from tkinter import ttk, messagebox


class App077:
    """色当てゲーム"""

    NUM_CHOICES = 6  # 選択肢の数

    def __init__(self, root):
        self.root = root
        self.root.title("色当てゲーム")
        self.root.geometry("520x534")
        self.root.minsize(520, 534)
        self.root.configure(bg="#f8f9fc")
        self.score = 0
        self.attempts = 0
        self.answer_index = 0
        self.colors = []
        self._build_ui()
        self.new_round()

    def _build_ui(self):
        """UIを構築する"""
        title_frame = tk.Frame(self.root, bg="#3776ab", pady=12)
        title_frame.pack(fill=tk.X)
        tk.Label(
            title_frame, text="色当てゲーム",
            font=("Noto Sans JP", 16, "bold"),
            bg="#3776ab", fg="white"
        ).pack()

        main = tk.Frame(self.root, bg="#f8f9fc", padx=18, pady=14)
        main.pack(fill=tk.BOTH, expand=True)

        # お題RGB
        self.question_var = tk.StringVar()
        tk.Label(main, textvariable=self.question_var, bg="#f8f9fc",
                 font=("Noto Sans JP", 14, "bold")).pack(pady=4)

        tk.Label(main, text="↓ 上のRGB値に対応する色をクリック",
                 bg="#f8f9fc", font=("Noto Sans JP", 10)).pack()

        # キャンバス（色の選択肢を 2x3 で並べる）
        self.canvas = tk.Canvas(main, width=420, height=300, bg="#f8f9fc",
                                 highlightthickness=0)
        self.canvas.pack(pady=10)
        self.canvas.bind("<Button-1>", self._on_click)

        # スコア
        self.status_var = tk.StringVar()
        tk.Label(main, textvariable=self.status_var, bg="#f8f9fc",
                 font=("Noto Sans JP", 11)).pack(pady=4)

        # ボタン
        btns = tk.Frame(main, bg="#f8f9fc")
        btns.pack()
        ttk.Button(btns, text="次の問題", command=self.new_round).pack(side=tk.LEFT, padx=4)
        ttk.Button(btns, text="リセット", command=self.reset).pack(side=tk.LEFT, padx=4)

    def _random_color(self):
        """ランダムな (r,g,b) を返す"""
        return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

    def new_round(self):
        """新しい問題を生成"""
        self.colors = [self._random_color() for _ in range(self.NUM_CHOICES)]
        self.answer_index = random.randint(0, self.NUM_CHOICES - 1)
        r, g, b = self.colors[self.answer_index]
        self.question_var.set(f"お題: RGB({r}, {g}, {b})")
        self._draw_choices()
        self._update_status()

    def _draw_choices(self, highlight=None, mark_correct=None):
        """選択肢タイルを描画"""
        self.canvas.delete("all")
        cols = 3
        rows = (self.NUM_CHOICES + cols - 1) // cols
        cell_w = 420 // cols
        cell_h = 300 // rows
        self._tile_rects = []  # (idx, x1, y1, x2, y2)
        for i, (r, g, b) in enumerate(self.colors):
            cx = i % cols
            cy = i // cols
            x1 = cx * cell_w + 6
            y1 = cy * cell_h + 6
            x2 = (cx + 1) * cell_w - 6
            y2 = (cy + 1) * cell_h - 6
            color = f"#{r:02x}{g:02x}{b:02x}"
            outline = "#333"
            width = 2
            if highlight is not None and i == highlight:
                outline = "#ff5500"
                width = 4
            if mark_correct is not None and i == mark_correct:
                outline = "#00aa00"
                width = 4
            self.canvas.create_rectangle(x1, y1, x2, y2, fill=color,
                                          outline=outline, width=width)
            self._tile_rects.append((i, x1, y1, x2, y2))

    def _on_click(self, event):
        """タイルクリック判定"""
        for idx, x1, y1, x2, y2 in self._tile_rects:
            if x1 <= event.x <= x2 and y1 <= event.y <= y2:
                self.attempts += 1
                if idx == self.answer_index:
                    self.score += 1
                    self._draw_choices(mark_correct=idx)
                    self._update_status()
                    self.root.after(700, self.new_round)
                else:
                    self._draw_choices(highlight=idx, mark_correct=self.answer_index)
                    self._update_status()
                    messagebox.showinfo(
                        "残念!",
                        f"正解は緑枠のタイルでした。\n"
                        f"あなたの選択: RGB{self.colors[idx]}"
                    )
                    self.root.after(200, self.new_round)
                break

    def _update_status(self):
        """スコア表示更新"""
        rate = (self.score / self.attempts * 100) if self.attempts else 0
        self.status_var.set(
            f"正解 {self.score} / 出題 {self.attempts}（正答率 {rate:.0f}%）"
        )

    def reset(self):
        """スコアリセット"""
        self.score = 0
        self.attempts = 0
        self.new_round()


if __name__ == "__main__":
    root = tk.Tk()
    app = App077(root)
    root.mainloop()
