import tkinter as tk
import math
import random
import time

# ========================
# 全局配置
# ========================
WIDTH, HEIGHT = 900, 600
FPS = 30
GRID_COLS, GRID_ROWS = 6, 4
CELL_SIZE = 110
GRID_X = (WIDTH - GRID_COLS * CELL_SIZE) // 2
GRID_Y = 120

# ========================
# 作物定义
# ========================
CROPS = {
    "wheat":   {"name": "🌾小麦", "color": "#F4D03F", "grow": [0, 20, 40, 60], "yield": 3, "sell": 10, "cost": 5,  "water": 3, "desc": "基础作物，生长快"},
    "carrot":  {"name": "🥕胡萝卜", "color": "#E67E22", "grow": [0, 30, 60, 90], "yield": 2, "sell": 18, "cost": 8,  "water": 4, "desc": "中等收益"},
    "tomato":  {"name": "🍅番茄", "color": "#E74C3C", "grow": [0, 40, 80, 120], "yield": 3, "sell": 25, "cost": 12, "water": 5, "desc": "高收益"},
    "corn":    {"name": "🌽玉米", "color": "#F39C12", "grow": [0, 50, 100, 150], "yield": 4, "sell": 35, "cost": 18, "water": 6, "desc": "高产作物"},
    "pumpkin": {"name": "🎃南瓜", "color": "#D35400", "grow": [0, 60, 130, 200], "yield": 2, "sell": 60, "cost": 30, "water": 8, "desc": "高级作物，周期长"},
    "starfruit":{"name": "⭐星果", "color": "#9B59B6", "grow": [0, 80, 160, 250], "yield": 1, "sell": 120, "cost": 50, "water": 10, "desc": "传说作物"},
}

# ========================
# 游戏状态（✅ 全部提前定义）
# ========================
grid = []          # 6x4 地块
coins = 100
day = 1
time_of_day = 0    # 0~240（一天240tick）
paused = False
selected_crop = "wheat"
selected_tool = "hoe"  # hoe/water/seed/harvest
message = ""
message_time = 0
weather = "☀️ 晴天"
inventory = {}     # 作物名 -> 数量
achievements = []
total_harvest = 0
total_earn = 0
combo = 0
particles = []

# ========================
# Tkinter
# ========================
root = tk.Tk()
root.title("🌾 农家乐 · 种菜游戏")
root.resizable(False, False)

canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, highlightthickness=0)
canvas.pack()

panel = tk.Frame(root)
panel.pack(fill="x")

info = tk.Label(panel, font=("Comic Sans MS", 10))
info.pack(side="left", padx=10)

msg_label = tk.Label(panel, font=("Comic Sans MS", 10, "bold"))
msg_label.pack(side="left", padx=20)

# ========================
# 主题
# ========================
themes = {
    "🌿 春日田园": {"bg": "#87CEEB", "fg": "#2E7D32", "soil": "#8D6E63", "soil_dry": "#A1887F"},
    "🌙 月夜农场": {"bg": "#1A1A3E", "fg": "#CE93D8", "soil": "#4E342E", "soil_dry": "#5D4037"},
    "🍂 金秋丰收": {"bg": "#FFF3E0", "fg": "#BF360C", "soil": "#795548", "soil_dry": "#8D6E63"},
    "❄️ 冬日雪原": {"bg": "#ECEFF1", "fg": "#37474F", "soil": "#B0BEC5", "soil_dry": "#90A4AE"},
    "🌴 热带农场": {"bg": "#E8F5E9", "fg": "#1B5E20", "soil": "#5D4037", "soil_dry": "#795548"},
    "🌋 火山农场": {"bg": "#3E2723", "fg": "#FF6F00", "soil": "#4E342E", "soil_dry": "#6D4C41"},
}

current_theme = "🌿 春日田园"

def apply_theme(name):
    global current_theme
    current_theme = name
    t = themes[name]
    root.configure(bg=t["bg"])
    panel.configure(bg=t["bg"])
    info.configure(bg=t["bg"], fg=t["fg"])
    msg_label.configure(bg=t["bg"], fg=t["fg"])
    canvas.configure(background=t["bg"])

# ========================
# 地块初始化
# ========================
def init_grid():
    global grid
    grid = []
    for r in range(GRID_ROWS):
        row = []
        for c in range(GRID_COLS):
            row.append({
                "crop": None,       # 作物类型
                "stage": 0,         # 0=空, 1=种子, 2=生长, 3=成熟
                "water": 0,         # 水分 0~10
                "fertilizer": 0,    # 肥料 0~3
                "age": 0,           # 生长计时
                "x": GRID_X + c * CELL_SIZE,
                "y": GRID_Y + r * CELL_SIZE,
            })
        grid.append(row)

# ========================
# 工具函数
# ========================
def cell_center(cell):
    return cell["x"] + CELL_SIZE // 2, cell["y"] + CELL_SIZE // 2

def get_cell_at(x, y):
    for r in range(GRID_ROWS):
        for c in range(GRID_COLS):
            cell = grid[r][c]
            if cell["x"] <= x < cell["x"] + CELL_SIZE and \
               cell["y"] <= y < cell["y"] + CELL_SIZE:
                return cell, r, c
    return None, -1, -1

def set_message(text):
    global message, message_time
    message = text
    message_time = 120

def add_particles(x, y, color, count=8):
    for _ in range(count):
        particles.append({
            "x": x, "y": y,
            "dx": random.uniform(-3, 3),
            "dy": random.uniform(-4, -1),
            "c": color,
            "life": random.randint(15, 30),
            "size": random.randint(2, 5)
        })

# ========================
# 游戏逻辑
# ========================
def tick_game():
    global day, time_of_day, message_time, combo

    if paused:
        return

    time_of_day += 1
    if time_of_day >= 240:
        time_of_day = 0
        day += 1
        set_message(f"🌅 第 {day} 天开始了！")
        # 每天水分自然蒸发
        for row in grid:
            for cell in row:
                if cell["crop"]:
                    cell["water"] = max(0, cell["water"] - 2)

    # 生长逻辑
    for row in grid:
        for cell in row:
            if cell["crop"] and cell["stage"] < 3:
                crop = CROPS[cell["crop"]]
                # 需要水分才能生长
                if cell["water"] > 0:
                    speed = 1 + cell["fertilizer"] * 0.3
                    cell["age"] += speed
                    cell["water"] -= 0.02
                # 阶段判定
                for i in range(3):
                    if cell["age"] >= crop["grow"][i + 1] and cell["stage"] <= i:
                        cell["stage"] = i + 1
                        cx, cy = cell_center(cell)
                        add_particles(cx, cy, crop["color"], 5)

    # 天气影响
    if weather == "🌧️ 雨天":
        for row in grid:
            for cell in row:
                if cell["crop"]:
                    cell["water"] = min(10, cell["water"] + 0.05)

    if message_time > 0:
        message_time -= 1

# ========================
# 玩家操作
# ========================
def use_tool(cell):
    global coins, inventory, total_harvest, total_earn, combo

    if selected_tool == "hoe":
        if cell["crop"] is None:
            set_message("地块已经是空的，选择种子种植吧！")
        else:
            set_message("先用收获工具收走作物")

    elif selected_tool == "water":
        if cell["crop"] is None:
            set_message("❌ 这里没有作物需要浇水")
        else:
            cell["water"] = min(10, cell["water"] + 3)
            cx, cy = cell_center(cell)
            add_particles(cx, cy - 10, "#42A5F5", 6)
            set_message("💧 浇水完成！")

    elif selected_tool == "seed":
        if cell["crop"] is not None:
            set_message("❌ 这里已经有作物了")
        else:
            crop = CROPS[selected_crop]
            if coins < crop["cost"]:
                set_message(f"❌ 金币不足！需要 {crop['cost']} 金")
            else:
                coins -= crop["cost"]
                cell["crop"] = selected_crop
                cell["stage"] = 1
                cell["age"] = 0
                cell["water"] = 5
                cx, cy = cell_center(cell)
                add_particles(cx, cy, crop["color"], 8)
                set_message(f"🌱 种下了{crop['name']}！")

    elif selected_tool == "harvest":
        if cell["crop"] is None:
            set_message("❌ 这里没有可收获的作物")
        elif cell["stage"] < 3:
            crop = CROPS[cell["crop"]]
            pct = int(cell["age"] / crop["grow"][3] * 100)
            set_message(f"⏳ {crop['name']}还没成熟 ({pct}%)")
        else:
            crop = CROPS[cell["crop"]]
            yield_count = crop["yield"] + cell["fertilizer"]
            cell["crop"] = None
            cell["stage"] = 0
            cell["age"] = 0
            cell["water"] = 0
            cell["fertilizer"] = 0
            inv_name = crop["name"]
            inventory[inv_name] = inventory.get(inv_name, 0) + yield_count
            earn = yield_count * crop["sell"]
            coins += earn
            total_harvest += yield_count
            total_earn += earn
            combo += 1
            cx, cy = cell_center(cell)
            add_particles(cx, cy, crop["color"], 12)
            set_message(f"✅ 收获 {yield_count}个{crop['name']}！+{earn}金 (连击x{combo})")
            check_achievements()

def use_fertilizer(cell):
    if cell["crop"] is None:
        set_message("❌ 先种作物再施肥")
        return
    if cell["fertilizer"] >= 3:
        set_message("❌ 肥料已满")
        return
    if coins < 5:
        set_message("❌ 金币不足（肥料5金）")
        return
    coins -= 5
    cell["fertilizer"] += 1
    cx, cy = cell_center(cell)
    add_particles(cx, cy, "#8BC34A", 6)
    set_message(f"💩 施肥成功！肥力+1 (当前{cell['fertilizer']})")

# ========================
# 成就系统
# ========================
ACHIEVEMENTS = [
    ("🌱 初次收获", lambda: total_harvest >= 1),
    ("🌾 丰收达人", lambda: total_harvest >= 20),
    ("💰 第一桶金", lambda: total_earn >= 100),
    ("💎 富翁", lambda: total_earn >= 500),
    ("⭐ 星果猎人", lambda: inventory.get("⭐星果", 0) >= 1),
    ("🔥 连击大师", lambda: combo >= 5),
    ("📅 老农夫", lambda: day >= 10),
    ("🎃 万圣节", lambda: inventory.get("🎃南瓜", 0) >= 3),
]

def check_achievements():
    for name, cond in ACHIEVEMENTS:
        if name not in achievements and cond():
            achievements.append(name)
            set_message(f"🏆 解锁成就：{name}！")

# ========================
# 商店
# ========================
def sell_all():
    global coins
    sold = 0
    for name, count in list(inventory.items()):
        # 找到对应crop
        for key, crop in CROPS.items():
            if crop["name"] == name:
                coins += count * crop["sell"]
                sold += count * crop["sell"]
                break
        inventory[name] = 0
    # 清掉0的
    for k in list(inventory.keys()):
        if inventory[k] == 0:
            del inventory[k]
    if sold > 0:
        set_message(f"💰 卖出所有作物！+{sold}金")
    else:
        set_message("📦 仓库是空的")

# ========================
# 绘制天空
# ========================
def draw_sky():
    canvas.delete("sky")
    # 根据时间变化
    if time_of_day < 60:       # 早晨
        top, bot = "#FF8A65", "#FFE0B2"
    elif time_of_day < 120:    # 正午
        top, bot = "#42A5F5", "#87CEEB"
    elif time_of_day < 180:    # 傍晚
        top, bot = "#AB47BC", "#FF7043"
    else:                      # 夜晚
        top, bot = "#1A237E", "#3949AB"

    if weather == "🌧️ 雨天":
        top, bot = "#37474F", "#546E7A"
    elif weather == "⛈️ 雷暴":
        top, bot = "#212121", "#424242"
    elif weather == "🌫️ 大雾":
        top, bot = "#B0BEC5", "#CFD8DC"
    elif weather == "🌈 彩虹天":
        top, bot = "#42A5F5", "#CE93D8"

    for y in range(GRID_Y):
        ratio = y / GRID_Y
        r = int(int(top[1:3], 16) * (1 - ratio) + int(bot[1:3], 16) * ratio)
        g = int(int(top[3:5], 16) * (1 - ratio) + int(bot[3:5], 16) * ratio)
        b = int(int(top[5:7], 16) * (1 - ratio) + int(bot[5:7], 16) * ratio)
        canvas.create_line(0, y, WIDTH, y, fill=f"#{r:02x}{g:02x}{b:02x}", tags="sky")

    # 太阳/月亮
    if time_of_day < 180:
        sx = int(WIDTH * 0.8)
        sy = 40 + int(30 * math.sin(math.pi * time_of_day / 180))
        for r in range(20, 36, 4):
            canvas.create_oval(sx - r, sy - r, sx + r, sy + r,
                                fill="#FFD600", outline="", tags="sky")
    else:
        mx = int(WIDTH * 0.8)
        my = 50
        canvas.create_oval(mx - 18, my - 18, mx + 18, my + 18,
                            fill="#FFF9C4", outline="", tags="sky")
        canvas.create_oval(mx - 8, my - 12, mx + 12, my + 8,
                            fill=top, outline="", tags="sky")

    # 雨/雪
    if weather == "🌧️ 雨天" or weather == "⛈️ 雷暴":
        for _ in range(40):
            rx = random.randint(0, WIDTH)
            ry = random.randint(0, GRID_Y)
            canvas.create_line(rx, ry, rx - 3, ry + 8,
                                fill="#90CAF9", width=1, tags="sky")
    elif weather == "❄️ 雪天":
        for _ in range(20):
            rx = random.randint(0, WIDTH)
            ry = random.randint(0, GRID_Y)
            canvas.create_text(rx, ry, text="❄", font=("", 8), fill="#E3F2FD", tags="sky")
    elif weather == "🌈 彩虹天":
        cols = ["#FF0000", "#FF7F00", "#FFFF00", "#00FF00", "#0000FF", "#4B0082", "#9400D3"]
        for i, c in enumerate(cols):
            canvas.create_arc(150 + i * 5, 20, WIDTH - 150, 120,
                                start=0, extent=180, style="arc",
                                outline=c, width=3, tags="sky")

# ========================
# 绘制地块
# ========================
def draw_grid():
    canvas.delete("grid")
    t = themes[current_theme]

    for r in range(GRID_ROWS):
        for c in range(GRID_COLS):
            cell = grid[r][c]
            x, y = cell["x"], cell["y"]

            # 地块背景
            if cell["crop"] is None:
                base_color = t["soil_dry"] if cell["water"] < 2 else t["soil"]
            else:
                base_color = t["soil"]
            canvas.create_rectangle(x + 2, y + 2, x + CELL_SIZE - 2, y + CELL_SIZE - 2,
                                    fill=base_color, outline="#5D4037", width=2, tags="grid")

            # 水分条
            if cell["crop"]:
                wx = x + 5
                wy = y + CELL_SIZE - 12
                canvas.create_rectangle(wx, wy, wx + (CELL_SIZE - 10), wy + 6,
                                        outline="#FFFFFF", width=1, tags="grid")
                wcolor = "#42A5F5" if cell["water"] > 3 else "#FF7043"
                canvas.create_rectangle(wx, wy, wx + int((CELL_SIZE - 10) * cell["water"] / 10), wy + 6,
                                        fill=wcolor, outline="", tags="grid")

                # 肥料标记
                if cell["fertilizer"] > 0:
                    canvas.create_text(x + CELL_SIZE - 12, y + 10,
                                        text="💩" * cell["fertilizer"],
                                        font=("", 8), tags="grid")

            # 作物绘制
            if cell["crop"]:
                crop = CROPS[cell["crop"]]
                cx, cy = cell_center(cell)

                if cell["stage"] == 1:    # 种子
                    canvas.create_oval(cx - 4, cy - 2, cx + 4, cy + 6,
                                        fill="#6D4C41", outline="", tags="grid")
                    canvas.create_line(cx, cy - 2, cx, cy - 10,
                                        fill="#4CAF50", width=2, tags="grid")
                elif cell["stage"] == 2:  # 生长
                    sz = CELL_SIZE * 0.25
                    canvas.create_rectangle(cx - sz * 0.3, cy, cx + sz * 0.3, cy + sz,
                                            fill=crop["color"], outline="", tags="grid")
                    canvas.create_line(cx, cy, cx - sz * 0.5, cy - sz * 0.8,
                                        fill="#4CAF50", width=2, tags="grid")
                    canvas.create_line(cx, cy, cx + sz * 0.5, cy - sz * 0.8,
                                        fill="#4CAF50", width=2, tags="grid")
                elif cell["stage"] == 3:  # 成熟
                    sz = CELL_SIZE * 0.35
                    canvas.create_rectangle(cx - sz * 0.4, cy - sz * 0.2, cx + sz * 0.4, cy + sz * 0.8,
                                            fill=crop["color"], outline="#333333", width=1, tags="grid")
                    # 叶子
                    canvas.create_oval(cx - sz * 0.6, cy - sz * 0.5, cx - sz * 0.1, cy - sz * 0.1,
                                        fill="#4CAF50", outline="", tags="grid")
                    canvas.create_oval(cx + sz * 0.1, cy - sz * 0.5, cx + sz * 0.6, cy - sz * 0.1,
                                        fill="#66BB6A", outline="", tags="grid")
                    # 成熟光晕
                    for rr in range(int(sz), int(sz) + 8, 2):
                        alpha_hex = "#FFD700"
                        canvas.create_oval(cx - rr * 0.7, cy - rr * 0.5,
                                            cx + rr * 0.7, cy + rr * 0.5,
                                            outline=alpha_hex, width=1, tags="grid")

                # 进度条
                pct = min(1.0, cell["age"] / crop["grow"][3])
                px = x + 5
                py = y + 5
                canvas.create_rectangle(px, py, px + (CELL_SIZE - 10), py + 4,
                                        outline="#FFFFFF", width=1, tags="grid")
                if pct < 1:
                    canvas.create_rectangle(px, py, px + int((CELL_SIZE - 10) * pct), py + 4,
                                            fill="#76FF03", outline="", tags="grid")
                else:
                    canvas.create_rectangle(px, py, px + (CELL_SIZE - 10), py + 4,
                                            fill="#FFD600", outline="", tags="grid")

# ========================
# 绘制工具栏
# ========================
TOOLS = [
    ("🔨 锄头", "hoe"),
    ("💧 水壶", "water"),
    ("🌱 播种", "seed"),
    ("✂️ 收获", "harvest"),
]

def draw_toolbar():
    canvas.delete("toolbar")
    # 底部工具栏背景
    canvas.create_rectangle(0, HEIGHT - 80, WIDTH, HEIGHT,
                            fill="#5D4037", outline="", tags="toolbar")

    # 工具按钮
    bx = 20
    by = HEIGHT - 70
    for label, tkey in TOOLS:
        bw = 90
        is_sel = (selected_tool == tkey)
        bg = "#8D6E63" if is_sel else "#6D4C41"
        canvas.create_rectangle(bx, by, bx + bw, by + 50,
                                fill=bg, outline="#3E2723", width=2, tags="toolbar")
        canvas.create_text(bx + bw // 2, by + 25, text=label,
                            fill="#FFFFFF", font=("Comic Sans MS", 10, "bold"), tags="toolbar")
        bx += bw + 10

    # 肥料按钮
    bx += 10
    canvas.create_rectangle(bx, by, bx + 90, by + 50,
                            fill="#689F38", outline="#33691E", width=2, tags="toolbar")
    canvas.create_text(bx + 45, by + 25, text="💩 施肥(5金)",
                        fill="#FFFFFF", font=("Comic Sans MS", 9, "bold"), tags="toolbar")

    # 出售按钮
    bx += 100
    canvas.create_rectangle(bx, by, bx + 100, by + 50,
                            fill="#D32F2F", outline="#B71C1C", width=2, tags="toolbar")
    canvas.create_text(bx + 50, by + 25, text="💰 出售全部",
                        fill="#FFFFFF", font=("Comic Sans MS", 10, "bold"), tags="toolbar")

# ========================
# 绘制种子选择
# ========================
def draw_seed_selector():
    canvas.delete("seedsel")
    sx = 20
    sy = 85
    canvas.create_text(sx, sy - 15, text="选择种子:", anchor="w",
                        fill="#FFFFFF", font=("Comic Sans MS", 9), tags="seedsel")

    for i, (key, crop) in enumerate(CROPS.items()):
        bx = sx + i * 140
        is_sel = (selected_crop == key)
        bg = "#C8E6C9" if is_sel else "#E8F5E9"
        canvas.create_rectangle(bx, sy, bx + 130, sy + 28,
                                fill=bg, outline="#2E7D32" if is_sel else "#A5D6A7",
                                width=2 if is_sel else 1, tags="seedsel")
        canvas.create_text(bx + 65, sy + 14,
                            text=f"{crop['name']} ({crop['cost']}金)",
                            fill="#1B5E20", font=("Comic Sans MS", 8), tags="seedsel")

# ========================
# 绘制HUD
# ========================
def draw_hud():
    canvas.delete("hud")

    # 顶部信息栏
    canvas.create_rectangle(0, 0, WIDTH, 40, fill="#2E7D32", outline="", tags="hud")
    time_str = f"{int(time_of_day / 10):02d}:{int((time_of_day % 10) * 6):02d}"
    canvas.create_text(10, 20, text=f"📅 第{day}天  {time_str}",
                        anchor="w", fill="#FFFFFF", font=("Comic Sans MS", 11, "bold"), tags="hud")
    canvas.create_text(WIDTH // 2, 20, text=f"💰 {coins} 金",
                        anchor="center", fill="#FFD600", font=("Comic Sans MS", 13, "bold"), tags="hud")
    canvas.create_text(WIDTH - 10, 20, text=f"🌤️ {weather}",
                        anchor="e", fill="#FFFFFF", font=("Comic Sans MS", 11), tags="hud")

    # 消息
    if message_time > 0:
        alpha = min(1.0, message_time / 60)
        msg_color = "#FFFFFF" if alpha > 0.5 else "#CCCCCC"
        canvas.create_text(WIDTH // 2, 55, text=message,
                            fill=msg_color, font=("Comic Sans MS", 11, "bold"), tags="hud")

    # 仓库
    inv_text = "📦 仓库: "
    for name, count in inventory.items():
        if count > 0:
            inv_text += f"{name}×{count}  "
    if not any(v > 0 for v in inventory.values()):
        inv_text += "空空如也"
    canvas.create_text(WIDTH // 2, HEIGHT - 90, text=inv_text,
                        fill="#FFE0B2", font=("Comic Sans MS", 9), tags="hud")

    # 成就
    if achievements:
        ach_text = "🏆 " + " | ".join(achievements[-3:])
        canvas.create_text(WIDTH - 10, HEIGHT - 90, text=ach_text,
                            anchor="e", fill="#FFD700",
                            font=("Comic Sans MS", 8), tags="hud")

    # 帮助
    help_text = "点击地块操作 | 底部选工具 | 顶部选种子 | 天气自动变化"
    canvas.create_text(WIDTH // 2, HEIGHT - 45, text=help_text,
                        fill="#D7CCC8", font=("Comic Sans MS", 8), tags="hud")

# ========================
# 绘制粒子
# ========================
def draw_particles():
    canvas.delete("particle")
    for p in particles[:]:
        sz = p["size"]
        canvas.create_oval(p["x"] - sz, p["y"] - sz, p["x"] + sz, p["y"] + sz,
                            fill=p["c"], outline="", tags="particle")
        p["x"] += p["dx"]
        p["y"] += p["dy"]
        p["dy"] += 0.15  # 重力
        p["life"] -= 1
        if p["life"] <= 0:
            particles.remove(p)

# ========================
# 场景绘制
# ========================
def draw_scene():
    draw_sky()
    draw_grid()
    draw_seed_selector()
    draw_toolbar()
    draw_particles()
    draw_hud()

# ========================
# 游戏循环
# ========================
def game_loop():
    global weather

    tick_game()

    # 天气随机变化（每天10%概率变）
    if random.random() < 0.001:
        weather = random.choice(["☀️ 晴天", "⛅ 多云", "🌧️ 雨天", "❄️ 雪天", "🌈 彩虹天", "⛈️ 雷暴", "🌫️ 大雾"])

    draw_scene()

    info.config(text=f"工具:{selected_tool} | 种子:{CROPS[selected_crop]['name']} | 连击:{combo}")

    root.after(int(1000 / FPS), game_loop)

# ========================
# 鼠标点击
# ========================
def on_click(e):
    global selected_tool, selected_crop

    # 检查工具按钮
    by = HEIGHT - 70
    bx = 20
    for label, tkey in TOOLS:
        bw = 90
        if bx <= e.x < bx + bw and by <= e.y < by + 50:
            selected_tool = tkey
            return
        bx += bw + 10

    # 施肥按钮
    fert_x = 20 + 4 * 100 + 30
    if 20 + 4 * 100 - 70 <= e.x < 20 + 4 * 100 + 30 and by <= e.y < by + 50:
        # 需要选中地块
        cell, r, c = get_cell_at(e.x, e.y)
        if cell and r >= 0:
            use_fertilizer(cell)
        return

    # 出售按钮
    sell_x = fert_x + 110
    if sell_x <= e.x < sell_x + 100 and by <= e.y < by + 50:
        sell_all()
        return

    # 种子选择
    sy = 85
    if 20 <= e.x < 20 + len(CROPS) * 140 and sy <= e.y < sy + 28:
        idx = (e.x - 20) // 140
        keys = list(CROPS.keys())
        if idx < len(keys):
            selected_crop = keys[idx]
        return

    # 地块操作
    cell, r, c = get_cell_at(e.x, e.y)
    if cell and r >= 0:
        use_tool(cell)

canvas.bind("<Button-1>", on_click)

# ========================
# 键盘快捷键
# ========================
def key_down(e):
    global paused, selected_tool, selected_crop, weather

    if e.keysym == "1":
        selected_tool = "hoe"
    elif e.keysym == "2":
        selected_tool = "water"
    elif e.keysym == "3":
        selected_tool = "seed"
    elif e.keysym == "4":
        selected_tool = "harvest"
    elif e.keysym == "p":
        paused = not paused
    elif e.keysym == "r":
        # 重新开始
        global coins, day, time_of_day, inventory, achievements, total_harvest, total_earn, combo
        coins = 100
        day = 1
        time_of_day = 0
        inventory = {}
        achievements = []
        total_harvest = total_earn = combo = 0
        particles.clear()
        init_grid()
        set_message("🔄 农场已重置！")
    elif e.keysym in ("5", "6", "7", "8", "9", "0"):
        keys = list(CROPS.keys())
        idx = int(e.keysym) - 5
        if 0 <= idx < len(keys):
            selected_crop = keys[idx]
    elif e.keysym == "w":
        weather = "🌧️ 雨天"
        set_message("🌧️ 天气变为雨天")
    elif e.keysym == "s":
        weather = "☀️ 晴天"
        set_message("☀️ 天气变为晴天")

root.bind("<KeyPress>", key_down)

# ========================
# 天气按钮
# ========================
weathers = ["☀️ 晴天", "⛅ 多云", "🌧️ 雨天", "❄️ 雪天", "🌈 彩虹天", "⛈️ 雷暴", "🌫️ 大雾"]
for w in weathers:
    tk.Button(panel, text=w, command=lambda w=w: globals().update(weather=w)).pack(side="left", padx=2)

# ========================
# 换肤按钮
# ========================
for name in themes:
    tk.Button(panel, text=name, command=lambda n=name: apply_theme(n)).pack(side="right", padx=2)

# ========================
# 启动
# ========================
init_grid()
apply_theme("🌿 春日田园")
set_message("🌾 欢迎来到农家乐！选种子→播种→浇水→收获→卖钱！")
game_loop()
root.mainloop()
