import tkinter as tk
import random
import time

# ============ 配置 ============
WIDTH, HEIGHT = 900, 650
GRID_ROWS, GRID_COLS = 3, 3
HOLE_W, HOLE_H = 160, 140
GAME_TIME = 60          # 总时长（秒）
MOLE_LIFETIME = (1.2, 2.2)   # 地鼠停留时间范围
SPAWN_INTERVAL = (0.5, 1.0)  # 出现间隔

# 数据类型池：每个类型给若干示例值
DATA_POOL = {
    "int": ["42", "-7", "2024", "0", "100"],
    "float": ["3.14", "2.5", "-0.01", "9.99", "1.0"],
    "str": ['"hello"', "'Python'", '"你好"', '"123"', "'abc'"],
    "bool": ["True", "False"],
    "list": ["[1,2,3]", "['a','b']", "[ ]", "[10,20]", "[]"],
    "dict": ["{'a':1}", "{'name':'Tom'}", "{ }", "{1:'x'}", "{}"],
    "NoneType": ["None", "None", "None"],
}

TYPE_NAMES = {
    "int": "整数 int",
    "float": "浮点数 float",
    "str": "字符串 str",
    "bool": "布尔 bool",
    "list": "列表 list",
    "dict": "字典 dict",
    "NoneType": "空值 None",
}

TYPE_COLORS = {
    "int": "#e74c3c",
    "float": "#e67e22",
    "str": "#27ae60",
    "bool": "#2980b9",
    "list": "#8e44ad",
    "dict": "#16a085",
    "NoneType": "#7f8c8d",
}


class Mole:
    """一只地鼠：包含数值、真实类型、位置、存活状态"""
    def __init__(self, hole_index, value, real_type, lifetime):
        self.hole_index = hole_index
        self.value = value
        self.real_type = real_type
        self.lifetime = lifetime
        self.born = time.time()
        self.hit = False


class WhackGame:
    def __init__(self, root):
        self.root = root
        self.root.title("🔨 打地鼠 · 识别数据类型")
        self.root.resizable(False, False)

        self.canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT,
                                bg="#87CEEB", highlightthickness=0)
        self.canvas.pack()

        # 游戏状态
        self.running = False
        self.score = 0
        self.combo = 0
        self.max_combo = 0
        self.mistakes = 0
        self.hits = 0
        self.start_time = 0
        self.target_type = None
        self.moles = {}       # hole_index -> Mole
        self.mole_items = {}  # hole_index -> canvas items
        self.next_spawn = 0
        self.time_left = GAME_TIME

        # 洞位置
        self.holes = []
        margin_x = (WIDTH - GRID_COLS * HOLE_W) // 2
        margin_y = 140
        for r in range(GRID_ROWS):
            for c in range(GRID_COLS):
                x = margin_x + c * HOLE_W
                y = margin_y + r * HOLE_H
                self.holes.append((x, y))

        # 绑定点击
        self.canvas.bind("<Button-1>", self.on_click)
        self.root.bind("<KeyPress-space>", lambda e: self.start_game())
        self.root.bind("<KeyPress-r>", lambda e: self.start_game())

        self.draw_start_screen()

    # ---------- 画面 ----------
    def draw_start_screen(self):
        c = self.canvas
        c.delete("all")
        # 背景草地
        c.create_rectangle(0, 0, WIDTH, HEIGHT, fill="#87CEEB", outline="")
        c.create_rectangle(0, 100, WIDTH, HEIGHT, fill="#7ec850", outline="")
        # 标题
        c.create_text(WIDTH // 2, 60, text="🔨 打地鼠 · 识别数据类型",
                      font=("Microsoft YaHei", 30, "bold"), fill="#2c3e50")
        c.create_text(WIDTH // 2, 300,
                      text="地鼠洞里会冒出各种数据值\n你只能打中【目标类型】的地鼠！\n\n打错或漏打都会影响分数",
                      font=("Microsoft YaHei", 18), fill="#2c3e50", justify="center")
        c.create_text(WIDTH // 2, 450, text="点击下方按钮开始",
                      font=("Microsoft YaHei", 16), fill="#555")
        # 开始按钮
        btn = c.create_rectangle(WIDTH // 2 - 120, 490, WIDTH // 2 + 120, 550,
                                 fill="#e67e22", outline="#d35400", width=3)
        c.create_text(WIDTH // 2, 520, text="▶ 开始游戏 (空格)",
                      font=("Microsoft YaHei", 18, "bold"), fill="white")
        c.tag_bind(btn, "<Button-1>", lambda e: self.start_game())
        c.create_text(WIDTH // 2, HEIGHT - 30,
                      text="规则：每局 60 秒，屏幕顶部显示目标类型，只打中该类型的地鼠",
                      font=("Microsoft YaHei", 12), fill="#333")

    def draw_holes(self):
        c = self.canvas
        # 草地背景
        c.create_rectangle(0, 0, WIDTH, HEIGHT, fill="#87CEEB", outline="")
        c.create_rectangle(0, 100, WIDTH, HEIGHT, fill="#7ec850", outline="")
        # 顶部信息栏
        c.create_rectangle(0, 0, WIDTH, 100, fill="#2c3e50", outline="")
        # 每个洞
        for i, (x, y) in enumerate(self.holes):
            # 洞（椭圆）
            c.create_oval(x + 20, y + 70, x + HOLE_W - 20, y + HOLE_H - 10,
                          fill="#3d2b1f", outline="#2a1d14", width=3)
            c.create_oval(x + 30, y + 80, x + HOLE_W - 30, y + HOLE_H - 20,
                          fill="#1a0f08", outline="")
            # 洞前草
            c.create_arc(x + 15, y + 80, x + HOLE_W - 15, y + HOLE_H + 10,
                         start=0, extent=180, fill="#5cb83a", outline="#4a9a2e")
            # 编号
            c.create_text(x + HOLE_W // 2, y + HOLE_H + 20,
                          text=f"洞 {i+1}", font=("Microsoft YaHei", 10),
                          fill="#2c3e50")

    def draw_top_bar(self):
        c = self.canvas
        # 清掉顶部文字重画
        c.delete("topbar")
        c.create_rectangle(0, 0, WIDTH, 100, fill="#2c3e50", outline="", tags="topbar")
        # 分数
        c.create_text(20, 25, text=f"分数: {self.score}", anchor="w",
                      font=("Microsoft YaHei", 18, "bold"), fill="#f1c40f", tags="topbar")
        # 连击
        combo_color = "#e74c3c" if self.combo >= 3 else "#ecf0f1"
        c.create_text(20, 60, text=f"连击: {self.combo}", anchor="w",
                      font=("Microsoft YaHei", 14), fill=combo_color, tags="topbar")
        # 目标类型
        if self.target_type:
            c.create_text(WIDTH // 2, 25, text="🎯 只打这种类型：",
                          font=("Microsoft YaHei", 14), fill="#ecf0f1", tags="topbar")
            c.create_text(WIDTH // 2, 60, text=TYPE_NAMES[self.target_type],
                          font=("Microsoft YaHei", 22, "bold"),
                          fill=TYPE_COLORS[self.target_type], tags="topbar")
        # 时间
        time_color = "#e74c3c" if self.time_left <= 10 else "#ecf0f1"
        c.create_text(WIDTH - 20, 25, text=f"⏱ {self.time_left:.0f}s", anchor="e",
                      font=("Microsoft YaHei", 18, "bold"), fill=time_color, tags="topbar")
        # 失误
        c.create_text(WIDTH - 20, 60, text=f"失误: {self.mistakes}", anchor="e",
                      font=("Microsoft YaHei", 14), fill="#ecf0f1", tags="topbar")

    # ---------- 游戏流程 ----------
    def start_game(self):
        self.running = True
        self.score = 0
        self.combo = 0
        self.max_combo = 0
        self.mistakes = 0
        self.hits = 0
        self.time_left = GAME_TIME
        self.moles.clear()
        self.mole_items.clear()
        self.start_time = time.time()
        self.next_spawn = time.time() + 0.6
        # 随机选目标类型
        self.target_type = random.choice(list(DATA_POOL.keys()))
        self.draw_holes()
        self.draw_top_bar()
        self.root.after(50, self.tick)

    def spawn_mole(self):
        # 找一个空的洞
        empty = [i for i in range(len(self.holes)) if i not in self.moles]
        if not empty:
            return
        idx = random.choice(empty)
        # 70% 概率生成目标类型，30% 生成其他类型
        if random.random() < 0.45:
            rt = self.target_type
        else:
            rt = random.choice(list(DATA_POOL.keys()))
        value = random.choice(DATA_POOL[rt])
        lifetime = random.uniform(*MOLE_LIFETIME)
        mole = Mole(idx, value, rt, lifetime)
        self.moles[idx] = mole
        self.draw_mole(mole)

    def draw_mole(self, mole):
        c = self.canvas
        x, y = self.holes[mole.hole_index]
        # 先删除旧的
        self.erase_mole(mole.hole_index)
        # 地鼠身体（棕色圆）
        body = c.create_oval(x + 40, y + 20, x + HOLE_W - 40, y + HOLE_H - 5,
                             fill="#a0522d", outline="#5c3317", width=2)
        # 耳朵
        e1 = c.create_oval(x + 45, y + 15, x + 75, y + 45,
                           fill="#8b4513", outline="#5c3317")
        e2 = c.create_oval(x + HOLE_W - 75, y + 15, x + HOLE_W - 45, y + 45,
                           fill="#8b4513", outline="#5c3317")
        # 眼睛
        eye1 = c.create_oval(x + 60, y + 55, x + 74, y + 69, fill="white", outline="black")
        eye2 = c.create_oval(x + HOLE_W - 74, y + 55, x + HOLE_W - 60, y + 69,
                             fill="white", outline="black")
        p1 = c.create_oval(x + 64, y + 59, x + 70, y + 65, fill="black")
        p2 = c.create_oval(x + HOLE_W - 70, y + 59, x + HOLE_W - 64, y + 65, fill="black")
        # 鼻子
        nose = c.create_oval(x + HOLE_W // 2 - 5, y + 72, x + HOLE_W // 2 + 5, y + 82,
                             fill="#5c3317", outline="")
        # 数值文本（在身体上）
        text = c.create_text(x + HOLE_W // 2, y + 95,
                             text=mole.value,
                             font=("Consolas", 14, "bold"),
                             fill="white")
        self.mole_items[mole.hole_index] = [body, e1, e2, eye1, eye2, p1, p2, nose, text]

    def erase_mole(self, hole_index):
        for it in self.mole_items.get(hole_index, []):
            self.canvas.delete(it)
        self.mole_items.pop(hole_index, None)

    def tick(self):
        if not self.running:
            return
        now = time.time()
        elapsed = now - self.start_time
        self.time_left = max(0, GAME_TIME - elapsed)
        if self.time_left <= 0:
            self.end_game()
            return

        # 移除超时的地鼠（漏打不扣分，但断连击）
        for idx in list(self.moles.keys()):
            mole = self.moles[idx]
            if now - mole.born > mole.lifetime:
                self.erase_mole(idx)
                del self.moles[idx]
                if not mole.hit and mole.real_type == self.target_type:
                    # 漏打目标地鼠
                    self.combo = 0

        # 生成新地鼠
        if now >= self.next_spawn:
            self.spawn_mole()
            self.next_spawn = now + random.uniform(*SPAWN_INTERVAL)

        self.draw_top_bar()
        self.root.after(50, self.tick)

    def on_click(self, event):
        if not self.running:
            return
        x, y = event.x, event.y
        # 检查点到哪个洞
        for i, (hx, hy) in enumerate(self.holes):
            if hx <= x <= hx + HOLE_W and hy <= y <= hy + HOLE_H:
                if i in self.moles:
                    self.hit_mole(i)
                else:
                    # 打空
                    self.mistakes += 1
                    self.combo = 0
                    self.show_feedback(hx + HOLE_W // 2, hy + HOLE_H // 2,
                                       "打空了!", "#e74c3c")
                return

    def hit_mole(self, idx):
        mole = self.moles[idx]
        mole.hit = True
        x, y = self.holes[idx]
        cx, cy = x + HOLE_W // 2, y + HOLE_H // 2
        if mole.real_type == self.target_type:
            self.score += 10 + self.combo * 2
            self.combo += 1
            self.max_combo = max(self.max_combo, self.combo)
            self.hits += 1
            self.show_feedback(cx, cy, f"+{10 + (self.combo-1)*2}", "#27ae60")
            self.show_combo(cx, cy, self.combo)
        else:
            self.score = max(0, self.score - 5)
            self.mistakes += 1
            self.combo = 0
            self.show_feedback(cx, cy, "类型错误!", "#e74c3c")
            # 显示正确类型
            self.show_feedback(cx, cy + 30,
                               f"这是 {TYPE_NAMES[mole.real_type]}", "#f39c12")
        self.erase_mole(idx)
        del self.moles[idx]

    def show_feedback(self, x, y, text, color):
        item = self.canvas.create_text(x, y, text=text, fill=color,
                                       font=("Microsoft YaHei", 16, "bold"))
        def fade(step=0):
            if step > 10:
                self.canvas.delete(item)
                return
            try:
                self.canvas.move(item, 0, -4)
                self.canvas.tag_raise(item)
            except tk.TclError:
                return
            self.root.after(50, lambda: fade(step + 1))
        fade()

    def show_combo(self, x, y, combo):
        if combo < 2:
            return
        item = self.canvas.create_text(x, y - 25, text=f"连击 x{combo}",
                                       fill="#f1c40f",
                                       font=("Microsoft YaHei", 18, "bold"))
        def fade(step=0):
            if step > 15:
                self.canvas.delete(item)
                return
            try:
                self.canvas.move(item, 0, -3)
            except tk.TclError:
                return
            self.root.after(40, lambda: fade(step + 1))
        fade()

    # ---------- 结束 ----------
    def end_game(self):
        self.running = False
        for idx in list(self.moles.keys()):
            self.erase_mole(idx)
        self.moles.clear()

        c = self.canvas
        c.create_rectangle(0, 0, WIDTH, HEIGHT, fill="#2c3e50", outline="")
        c.create_text(WIDTH // 2, 120, text="⏰ 时间到！",
                      font=("Microsoft YaHei", 36, "bold"), fill="#f1c40f")
        c.create_text(WIDTH // 2, 200, text=f"最终得分: {self.score}",
                      font=("Microsoft YaHei", 28, "bold"), fill="white")
        c.create_text(WIDTH // 2, 260, text=f"命中目标: {self.hits} 次",
                      font=("Microsoft YaHei", 18), fill="#ecf0f1")
        c.create_text(WIDTH // 2, 300, text=f"失误: {self.mistakes} 次",
                      font=("Microsoft YaHei", 18), fill="#e74c3c")
        c.create_text(WIDTH // 2, 340, text=f"最高连击: {self.max_combo}",
                      font=("Microsoft YaHei", 18), fill="#f1c40f")
        # 评价
        if self.score >= 300 and self.mistakes <= 3:
            comment = "🏆 数据类型大师！"
        elif self.score >= 200:
            comment = "🌟 表现不错！"
        elif self.score >= 100:
            comment = "👍 继续加油！"
        else:
            comment = "💪 多练习几次吧"
        c.create_text(WIDTH // 2, 400, text=comment,
                      font=("Microsoft YaHei", 24, "bold"), fill="#2ecc71")
        # 重新开始按钮
        btn = c.create_rectangle(WIDTH // 2 - 120, 470, WIDTH // 2 + 120, 530,
                                 fill="#e67e22", outline="#d35400", width=3)
        c.create_text(WIDTH // 2, 500, text="🔄 再玩一次 (R)",
                      font=("Microsoft YaHei", 18, "bold"), fill="white")
        c.tag_bind(btn, "<Button-1>", lambda e: self.start_game())


if __name__ == "__main__":
    root = tk.Tk()
    game = WhackGame(root)
    root.mainloop()