import pygame
import random
import sys

# ===================== 基础配置 =====================
pygame.init()
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("农家乐种菜小游戏")
clock = pygame.time.Clock()
FPS = 60

# 颜色常量
WHITE = (255, 255, 255)
BROWN = (101, 67, 33)
GREEN = (34, 139, 34)
BLUE = (30, 144, 255)
YELLOW = (255, 215, 0)
RED = (220, 20, 60)
BLACK = (0, 0, 0)
GRAY = (120, 120, 120)

# 字体
font = pygame.font.SysFont("simhei", 24)
big_font = pygame.font.SysFont("simhei", 36)

# 农作物配置：生长总帧数、售价、名字、颜色
CROP_CONFIG = {
    "白菜": {"grow_time": 300, "price": 10, "color": GREEN},
    "番茄": {"grow_time": 450, "price": 20, "color": RED},
    "玉米": {"grow_time": 600, "price": 35, "color": YELLOW}
}
crop_list = list(CROP_CONFIG.keys())

# 地块参数
grid_cols = 4
grid_rows = 3
cell_w = 150
cell_h = 120
offset_x = 50
offset_y = 80

# 游戏全局变量
money = 50  # 初始金币
selected_crop = 0  # 当前选中种子下标
land_list = []  # 所有土地数据
# 土地状态：空、已播种、成熟
EMPTY = 0
SEED = 1
MATURE = 2

# 初始化全部土地
for row in range(grid_rows):
    row_data = []
    for col in range(grid_cols):
        land_info = {
            "status": EMPTY,
            "crop_name": "",
            "grow_frame": 0,  # 已生长帧数
            "watered": False  # 是否浇水，没浇水停止生长
        }
        row_data.append(land_info)
    land_list.append(row_data)


# ===================== 工具函数 =====================
def draw_text(text, x, y, color=BLACK, f=font):
    render = f.render(text, True, color)
    screen.blit(render, (x, y))


def get_mouse_grid(mx, my):
    """鼠标坐标转为地块行列，超出返回None"""
    col = (mx - offset_x) // cell_w
    row = (my - offset_y) // cell_h
    if 0 <= col < grid_cols and 0 <= row < grid_rows:
        return row, col
    return None


# ===================== 主循环 =====================
running = True
while running:
    dt = clock.tick(FPS)
    screen.fill((135, 206, 235))  # 天空蓝背景

    # 事件循环
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # 鼠标左键点击地块
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            m_x, m_y = pygame.mouse.get_pos()
            pos = get_mouse_grid(m_x, m_y)
            if pos is not None:
                r, c = pos
                land = land_list[r][c]
                # 空地播种（花费5金币）
                if land["status"] == EMPTY and money >= 5:
                    money -= 5
                    land["status"] = SEED
                    land["crop_name"] = crop_list[selected_crop]
                    land["grow_frame"] = 0
                    land["watered"] = False
                # 成熟收获
                elif land["status"] == MATURE:
                    crop = land["crop_name"]
                    money += CROP_CONFIG[crop]["price"]
                    # 土地重置为空
                    land["status"] = EMPTY
                    land["crop_name"] = ""
                    land["grow_frame"] = 0
                # 未成熟作物浇水
                elif land["status"] == SEED and not land["watered"]:
                    land["watered"] = True

        # 键盘切换种子 1/2/3
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_1:
                selected_crop = 0
            elif event.key == pygame.K_2:
                selected_crop = 1
            elif event.key == pygame.K_3:
                selected_crop = 2

    # 作物生长逻辑：只有浇过水才涨进度
    for r in range(grid_rows):
        for c in range(grid_cols):
            land = land_list[r][c]
            if land["status"] == SEED and land["watered"]:
                land["grow_frame"] += 1
                total = CROP_CONFIG[land["crop_name"]]["grow_time"]
                if land["grow_frame"] >= total:
                    land["status"] = MATURE

    # ========== 绘制土地 ==========
    for r in range(grid_rows):
        for c in range(grid_cols):
            x = offset_x + c * cell_w
            y = offset_y + r * cell_h
            land = land_list[r][c]
            # 土地底色
            pygame.draw.rect(screen, BROWN, (x, y, cell_w - 4, cell_h - 4))
            pygame.draw.rect(screen, BLACK, (x, y, cell_w - 4, cell_h - 4), 2)

            # 空地
            if land["status"] == EMPTY:
                draw_text("空地", x + 45, y + 45, WHITE)
            # 播种生长期
            elif land["status"] == SEED:
                crop = land["crop_name"]
                cfg = CROP_CONFIG[crop]
                progress = land["grow_frame"] / cfg["grow_time"]
                # 生长进度条
                bar_w = 100
                pygame.draw.rect(screen, GRAY, (x + 20, y + 70, bar_w, 12))
                pygame.draw.rect(screen, GREEN, (x + 20, y + 70, bar_w * progress, 12))
                # 浇水状态
                water_txt = "已浇水" if land["watered"] else "缺水"
                draw_text(f"{crop}", x + 35, y + 10, cfg["color"])
                draw_text(water_txt, x + 35, y + 30, BLUE if land["watered"] else RED)
            # 成熟可收获
            elif land["status"] == MATURE:
                crop = land["crop_name"]
                cfg = CROP_CONFIG[crop]
                pygame.draw.circle(screen, cfg["color"], (x + 70, y + 55), 30)
                draw_text("点击收获", x + 22, y + 90, YELLOW)

    # ========== 顶部UI信息 ==========
    draw_text(f"金币：{money}", 20, 15, YELLOW, big_font)
    draw_text("按 1白菜 2番茄 3玉米切换种子 | 播种消耗5金币", 220, 20, BLACK)
    current_seed = crop_list[selected_crop]
    draw_text(f"当前种子：{current_seed}", 520, 15, RED, big_font)

    # 底部操作提示
    draw_text("操作：左键空地播种 | 左键作物浇水 | 左键成熟田地收割卖钱", 30, 530, BLACK)

    pygame.display.flip()

pygame.quit()
sys.exit()