import tkinter as tk

# ================= 游戏配置 =================
ROWS, COLS = 4, 4                # 田地大小
PLOT_SIZE = 80                   # 每个格子像素大小
PADDING = 5                      # 格子间距
WINDOW_W = COLS * PLOT_SIZE + (COLS + 1) * PADDING
WINDOW_H = ROWS * PLOT_SIZE + (ROWS + 1) * PADDING + 60  # 顶部留给金币显示

# 生长参数（秒）
GROW_STAGE_TIME = 3              # 每阶段需要 3 秒
DRY_TIME = 5                     # 5 秒不浇水就干旱
# 经济
SEED_COST = 10
HARVEST_INCOME = 30
INITIAL_GOLD = 100

# ================= 地块数据模型 =================
class Plot:
    def __init__(self):
        self.crop = None          # None 或 "wheat"
        self.stage = 0            # 0:种子 1:幼苗 2:成长 3:成熟
        self.watered = True
        self.dry_timer = 0        # 距上次浇水秒数
        self.grow_counter = 0     # 当前阶段已成长秒数

    def reset(self):
        self.crop = None
        self.stage = 0
        self.watered = True
        self.dry_timer = 0
        self.grow_counter = 0

    def plant(self, crop_type):
        self.crop = crop_type
        self.stage = 0
        self.watered = True
        self.dry_timer = 0
        self.grow_counter = 0

    def is_empty(self):
        return self.crop is None

    def is_mature(self):
        return self.crop is not None and self.stage == 3

# ================= 主游戏类 =================
class FarmGame:
    def __init__(self, master):
        self.master = master
        master.title("🌾 农家乐种菜游戏")
        self.gold = INITIAL_GOLD

        # 状态栏
        self.status_label = tk.Label(master, text=f"金币: {self.gold}", font=("Arial", 16))
        self.status_label.pack(pady=5)

        # 画布
        self.canvas = tk.Canvas(master, width=WINDOW_W, height=WINDOW_H-60, bg="#f5f5dc")
        self.canvas.pack()
        self.canvas.bind("<Button-1>", self.on_click)

        # 初始化地块
        self.plots = [[Plot() for _ in range(COLS)] for _ in range(ROWS)]
        self.draw_all_plots()

        # 启动游戏循环（每秒更新）
        self.update_game()

    # ---------- 绘制 ----------
    def get_plot_rect(self, r, c):
        """返回格子左上角坐标"""
        x0 = PADDING + c * (PLOT_SIZE + PADDING)
        y0 = PADDING + r * (PLOT_SIZE + PADDING)
        return x0, y0, x0 + PLOT_SIZE, y0 + PLOT_SIZE

    def draw_all_plots(self):
        self.canvas.delete("all")
        for r in range(ROWS):
            for c in range(COLS):
                self.draw_plot(r, c)

    def draw_plot(self, r, c):
        x0, y0, x1, y1 = self.get_plot_rect(r, c)
        plot = self.plots[r][c]

        # 颜色与文字
        if plot.is_empty():
            color = "#deb887"      # 浅棕色空地
            text = "空地"
        elif plot.crop == "wheat":
            if plot.stage == 0:
                color = "#8b4513"  # 深棕色种子
                text = "🌱种子"
            elif plot.stage == 1:
                color = "#90ee90"  # 浅绿幼苗
                text = "幼苗"
            elif plot.stage == 2:
                color = "#228b22"  # 绿色成长
                text = "成长"
            else:  # stage == 3
                color = "#ffd700"  # 金色成熟
                text = "🌾成熟"
        else:
            color = "gray"
            text = "???"

        # 绘制格子
        self.canvas.create_rectangle(x0, y0, x1, y1, fill=color, outline="black", width=2)
        self.canvas.create_text((x0+x1)//2, (y0+y1)//2, text=text, font=("Arial", 12, "bold"))

        # 如果干旱且非空地非成熟，加个缺水标识
        if not plot.is_empty() and not plot.is_mature() and not plot.watered:
            self.canvas.create_text((x0+x1)//2, y1-12, text="💧缺水", font=("Arial", 9), fill="red")

    # ---------- 点击处理 ----------
    def on_click(self, event):
        # 根据坐标算出格子
        c = (event.x - PADDING) // (PLOT_SIZE + PADDING)
        r = (event.y - PADDING) // (PLOT_SIZE + PADDING)
        if 0 <= r < ROWS and 0 <= c < COLS:
            plot = self.plots[r][c]
            if plot.is_empty():
                # 空地：购买种子并种植
                if self.gold >= SEED_COST:
                    self.gold -= SEED_COST
                    plot.plant("wheat")
                    self.status_label.config(text=f"金币: {self.gold}")
                else:
                    self.show_message("金币不足！")
            elif plot.is_mature():
                # 成熟：收获
                self.gold += HARVEST_INCOME
                plot.reset()
                self.status_label.config(text=f"金币: {self.gold}")
            else:
                # 未成熟：浇水
                plot.watered = True
                plot.dry_timer = 0
                # 浇水本身不花金币
            self.draw_all_plots()

    def show_message(self, msg):
        top = tk.Toplevel(self.master)
        top.title("提示")
        tk.Label(top, text=msg, font=("Arial", 14)).pack(padx=20, pady=10)
        tk.Button(top, text="确定", command=top.destroy).pack(pady=5)

    # ---------- 游戏更新循环 ----------
    def update_game(self):
        for r in range(ROWS):
            for c in range(COLS):
                plot = self.plots[r][c]
                if plot.is_empty() or plot.is_mature():
                    continue  # 空地和成熟作物无需更新

                # 干旱计时
                plot.dry_timer += 1
                if plot.dry_timer >= DRY_TIME:
                    plot.watered = False

                # 生长：只有浇水状态下才累积生长进度
                if plot.watered:
                    plot.grow_counter += 1
                    if plot.grow_counter >= GROW_STAGE_TIME:
                        plot.grow_counter = 0
                        plot.stage += 1
                        # 进入下一阶段，重置干旱计时（刚浇水一样）
                        plot.dry_timer = 0
                        plot.watered = True
                        # 如果达到成熟，就不需要水了
        self.draw_all_plots()
        self.master.after(1000, self.update_game)   # 每秒更新

# ================= 启动 =================
if __name__ == "__main__":
    root = tk.Tk()
    game = FarmGame(root)
    root.mainloop()