import pygame
import math
import random

pygame.init()
W, H = 1200, 700
screen = pygame.display.set_mode((W, H))
pygame.display.set_caption("超级农家乐农场（含游戏说明书）")
clock = pygame.time.Clock()
FPS = 60

# 基础颜色
SKY_DAY = (135, 206, 235)
SKY_NIGHT = (15, 15, 50)
SKY_RAIN = (80, 90, 105)
GRASS_GREEN = (50, 160, 50)
SOIL_BROWN = (112, 78, 42)
SOIL_DRY = (75, 52, 28)
WATER_BLUE = (70, 150, 240)
UI_BG = (22, 22, 22, 190)
WHITE = (255,255,255)
GOLD = (255, 212, 0)
RED = (225, 25, 25)
GREEN_PLANT = (25, 190, 25)
YELLOW_RIPE = (242, 205, 20)
WEED_GREEN = (35, 85, 18)
BUG_BROWN = (55, 38, 28)
FRUIT_RED = (230, 60, 40)
CHICKEN_YELLOW = (245, 220, 70)
RAIN_DROP = (180, 210, 245, 100)

# 季节配置
SEASON_LIST = ["spring", "summer", "autumn", "winter"]
SEASON_COLOR = {
    "spring": (180, 230, 170),
    "summer": (70, 180, 50),
    "autumn": (200, 140, 60),
    "winter": (220, 230, 240)
}
# 作物数据：名称、种子价、出售价、生长时长、适配季节
CROP_DATA = {
    "wheat": {"name":"小麦", "seed_cost":5, "sell":20, "grow_time":8, "season":["spring","summer"]},
    "carrot": {"name":"胡萝卜", "seed_cost":8, "sell":35, "grow_time":12, "season":["spring","autumn"]},
    "tomato": {"name":"番茄", "seed_cost":15, "sell":60, "grow_time":18, "season":["summer"]},
    "cabbage": {"name":"白菜", "seed_cost":12, "sell":48, "grow_time":["autumn","winter"]},
}
# 果树数据
TREE_DATA = {
    "apple": {"name":"苹果树", "seed_cost":120, "sell":100, "grow_time":35}
}
# 家畜数据
ANIMAL_DATA = {
    "chicken": {"name":"小鸡", "buy_cost":80, "egg_price":25, "produce_cycle":12}
}
# 农具升级
TOOL_LEVEL = {
    "water": 1,
    "spray": 1,
    "sickle": 1
}
TOOL_MAX = 3
UPGRADE_COST = [0, 180, 450]

# 全局游戏数据
gold = 180
day_time = 0
day_length = 45
day_count = 1
season_idx = 0
current_season = SEASON_LIST[season_idx]
is_night = False
is_rain = False
rain_list = []
selected_tool = "seed_wheat"
inventory_seed = {"wheat":5, "carrot":3, "tomato":1, "cabbage":2, "apple":0}
warehouse = {}  # 仓库存放收获作物
animals = []  # 家畜列表
auto_sprinkler = False  # 自动洒水器解锁
orders = []  # 订单任务
flash_alpha = 0  # 成熟闪光

# 农田网格
grid_size = 72
grid_off_x = 280
grid_off_y = 110
grid_cols = 14
grid_rows = 6

# 地块类
class Plot:
    def __init__(self, gx, gy):
        self.gx = gx
        self.gy = gy
        self.is_wet = False
        self.wet_timer = 0
        self.crop_id = None
        self.tree_id = None
        self.grow_progress = 0
        self.max_grow = 0
        self.has_weed = False
        self.has_bug = False
        self.plant_anim = 0

# 生成农田
farm_plots = []
for y in range(grid_rows):
    row = []
    for x in range(grid_cols):
        row.append(Plot(x, y))
    farm_plots.append(row)

# 生成初始订单
def create_order():
    crop = random.choice(list(CROP_DATA.keys()))
    num = random.randint(3,8)
    reward = CROP_DATA[crop]["sell"] * num * 1.6
    return {"crop":crop, "need":num, "reward":int(reward)}
orders.append(create_order())

# 字体兼容兜底
try:
    font = pygame.font.SysFont("msyh", 20)
    font_small = pygame.font.SysFont("msyh", 15)
    font_big = pygame.font.SysFont("msyh", 28)
except:
    font = pygame.font.Font(None, 20)
    font_small = pygame.font.Font(None, 15)
    font_big = pygame.font.Font(None, 28)

# 生成雨滴
def spawn_rain():
    for _ in range(120):
        rain_list.append({
            "x": random.randint(0,W),
            "y": random.randint(-H,0),
            "speed": random.uniform(6,12),
            "len": random.randint(4,10)
        })

# 绘制地块、作物、果树
def draw_plot(plot):
    sx = grid_off_x + plot.gx * grid_size
    sy = grid_off_y + plot.gy * grid_size
    rect = (sx, sy, grid_size-3, grid_size-3)
    # 土地底色
    if plot.is_wet:
        pygame.draw.rect(screen, SOIL_BROWN, rect)
    else:
        pygame.draw.rect(screen, SOIL_DRY, rect)
    pygame.draw.rect(screen, (40,25,8), rect, 2)
    plot.plant_anim += 0.03

    # 杂草
    if plot.has_weed:
        sway = math.sin(plot.plant_anim) * 3
        pygame.draw.polygon(screen, WEED_GREEN, [
            (sx+24+sway, sy+62), (sx+30, sy+12), (sx+36-sway, sy+62)
        ])
    # 虫子
    if plot.has_bug:
        bug_x = sx + 52 + math.sin(plot.plant_anim*2)*4
        bug_y = sy + 50
        pygame.draw.circle(screen, BUG_BROWN, (int(bug_x), int(bug_y)), 7)

    # 普通农作物
    if plot.crop_id is not None:
        data = CROP_DATA[plot.crop_id]
        prog = plot.grow_progress / plot.max_grow
        cx = sx + grid_size//2
        cy = sy + grid_size - 10
        h = int(46 * prog)
        sway = math.sin(plot.plant_anim) * 2
        pygame.draw.line(screen, GREEN_PLANT, (cx+sway, cy), (cx+sway, cy-h), 3)
        # 成熟果实
        if prog >= 1:
            ripe_surf = pygame.Surface((22,22), pygame.SRCALPHA)
            ripe_surf.fill((*YELLOW_RIPE, flash_alpha))
            screen.blit(ripe_surf, (cx-11+sway, cy-h-11))
        else:
            pygame.draw.circle(screen, GREEN_PLANT, (cx+sway, cy-h), 6)
    # 果树
    if plot.tree_id is not None:
        prog = plot.grow_progress / plot.max_grow
        cx = sx + grid_size//2
        cy = sy + grid_size - 5
        tree_h = int(60 * prog)
        pygame.draw.rect(screen, (70,45,25), [cx-6, cy-tree_h, 12, tree_h])
        # 树冠果实
        r = int(28 * prog)
        pygame.draw.circle(screen, SEASON_COLOR[current_season], (cx, cy-tree_h), r)
        if prog >= 1:
            pygame.draw.circle(screen, FRUIT_RED, (cx-12, cy-tree_h-10), 7)
            pygame.draw.circle(screen, FRUIT_RED, (cx+12, cy-tree_h-6), 7)

# 绘制家畜
def draw_animals():
    for ani in animals:
        ax, ay, ani_type, timer = ani
        sway = math.sin(timer*1.5)*2
        if ani_type == "chicken":
            pygame.draw.circle(screen, CHICKEN_YELLOW, (int(ax+sway), int(ay)), 14)
            pygame.draw.polygon(screen, RED, [(ax+12, ay), (ax+24, ay-6), (ax+24, ay+6)])

# 绘制雨滴
def draw_rain():
    for drop in rain_list:
        pygame.draw.line(screen, RAIN_DROP, (drop["x"], drop["y"]), (drop["x"], drop["y"]+drop["len"]), 1)

# 左侧游戏说明书面板（新增）
def draw_manual():
    manual_w = 260
    manual_h = H - 20
    manual_surf = pygame.Surface((manual_w, manual_h), pygame.SRCALPHA)
    manual_surf.fill(UI_BG)
    pygame.draw.rect(manual_surf, WHITE, (0,0,manual_w,manual_h),3)
    # 标题
    title = font_big.render("📖 游戏说明书", True, GOLD)
    manual_surf.blit(title, (12, 10))
    y = 48
    # 一、基础操作
    line1 = font.render("【一、工具快捷键】", True, WHITE)
    manual_surf.blit(line1, (10, y))
    y += 26
    key_list = [
        "1=小麦种子  2=胡萝卜种子",
        "3=番茄种子  4=白菜种子",
        "5=苹果树苗  6=浇水壶",
        "7=镰刀收割  8=喷雾除虫除草",
        "鼠标左键：点击土地使用工具"
    ]
    for txt in key_list:
        t = font_small.render(txt, True, WHITE)
        manual_surf.blit(t, (12, y))
        y += 22
    y += 10
    # 二、商店购买按键
    line2 = font.render("【二、商店购买】", True, WHITE)
    manual_surf.blit(line2, (10, y))
    y += 26
    shop_key = [
        "M：自动购买最便宜种子",
        "T：购买苹果果树苗",
        "N：购买产蛋小鸡"
    ]
    for txt in shop_key:
        t = font_small.render(txt, True, WHITE)
        manual_surf.blit(t, (12, y))
        y += 22
    y += 10
    # 三、进阶功能按键
    line3 = font.render("【三、进阶功能】", True, WHITE)
    manual_surf.blit(line3, (10, y))
    y += 26
    adv_key = [
        "U：升级农具（浇水/镰刀/喷雾）",
        "Z：交付仓库作物完成订单"
    ]
    for txt in adv_key:
        t = font_small.render(txt, True, WHITE)
        manual_surf.blit(t, (12, y))
        y += 22
    y += 10
    # 四、种植规则
    line4 = font.render("【四、种植规则】", True, WHITE)
    manual_surf.blit(line4, (10, y))
    y += 26
    rule_list = [
        "1.土地干燥作物停止生长",
        "2.浇水维持湿润，下雨自动浇地",
        "3.杂草/虫害会完全阻断生长",
        "4.作物变黄=成熟，镰刀收割卖钱",
        "5.果树生长慢，可多次收割",
        "6.四季轮换，部分作物限定季节"
    ]
    for txt in rule_list:
        t = font_small.render(txt, True, WHITE)
        manual_surf.blit(t, (12, y))
        y += 22
    y += 10
    # 五、赚钱方式
    line5 = font.render("【五、赚钱途径】", True, WHITE)
    manual_surf.blit(line5, (10, y))
    y += 26
    money_list = [
        "①收割成熟作物直接变现",
        "②小鸡定时自动产出鸡蛋",
        "③完成订单获得高额奖金",
        "④果树长期稳定收获"
    ]
    for txt in money_list:
        t = font_small.render(txt, True, WHITE)
        manual_surf.blit(t, (12, y))
        y += 22
    # 绘制到屏幕最左侧
    screen.blit(manual_surf, (10, 10))

# 商店UI
def draw_shop():
    shop_surf = pygame.Surface((340, 280), pygame.SRCALPHA)
    shop_surf.fill(UI_BG)
    pygame.draw.rect(shop_surf, WHITE, (0,0,340,280),3)
    shop_surf.blit(font_big.render("农资商店", True, WHITE), (10, 8))
    y_off = 45
    # 种子
    for key in CROP_DATA:
        d = CROP_DATA[key]
        txt = font.render(f"{d['name']}种子 {d['seed_cost']}金", True, WHITE)
        shop_surf.blit(txt, (12, y_off))
        y_off += 34
    shop_surf.blit(font.render(f"苹果树 {TREE_DATA['apple']['seed_cost']}金", True, FRUIT_RED), (12, y_off))
    y_off +=34
    shop_surf.blit(font.render(f"小鸡 {ANIMAL_DATA['chicken']['buy_cost']}金", True, CHICKEN_YELLOW), (12,y_off))
    screen.blit(shop_surf, (W-350, 15))

# 订单面板
def draw_order_panel():
    if len(orders) <=0:
        return
    od = orders[0]
    od_surf = pygame.Surface((260, 110), pygame.SRCALPHA)
    od_surf.fill(UI_BG)
    pygame.draw.rect(od_surf, WHITE, (0,0,260,110),2)
    cname = CROP_DATA[od["crop"]]["name"]
    od_surf.blit(font.render(f"订单: {cname} x{od['need']}", True, WHITE), (10,10))
    od_surf.blit(font.render(f"奖励: {od['reward']}金币", True, GOLD), (10,40))
    od_surf.blit(font_small.render("Z键交付仓库作物", True, WHITE), (10,75))
    screen.blit(od_surf, (290, H-125))

# 底部工具栏
def draw_toolbar():
    bar_surf = pygame.Surface((910, 90), pygame.SRCALPHA)
    bar_surf.fill(UI_BG)
    pygame.draw.rect(bar_surf, WHITE, (0,0,910,90),2)
    tip1 = font.render("1~8切换工具 | M/T/N商店采购 | U升级农具 | Z交付订单", True, WHITE)
    tip2 = font.render(f"金币:{gold} | 当前工具:{selected_tool} | 季节:{current_season} 第{day_count}天", True, GOLD)
    tip3 = font_small.render(f"农具等级 浇水Lv{TOOL_LEVEL['water']} 镰刀Lv{TOOL_LEVEL['sickle']} 喷雾Lv{TOOL_LEVEL['spray']}", True, WHITE)
    bar_surf.blit(tip1, (12, 8))
    bar_surf.blit(tip2, (12, 38))
    bar_surf.blit(tip3, (12, 64))
    screen.blit(bar_surf, (280, H-100))

# 获取点击地块
def get_click_plot(mx, my):
    gx = (mx - grid_off_x) // grid_size
    gy = (my - grid_off_y) // grid_size
    if 0 <= gx < grid_cols and 0 <= gy < grid_rows:
        return farm_plots[gy][gx]
    return None

running = True
while running:
    dt = clock.tick(FPS)/1000
    mx, my = pygame.mouse.get_pos()
    click = False
    # 昼夜计时
    day_time += dt
    if day_time >= day_length:
        day_time = 0
        day_count += 1
        # 季节切换
        if day_count % 22 == 0:
            season_idx = (season_idx + 1) % 4
            current_season = SEASON_LIST[season_idx]
        # 随机下雨
        if random.random() < 0.28 and not is_rain:
            is_rain = True
            spawn_rain()
        else:
            is_rain = False
            rain_list.clear()
    is_night = day_time > day_length * 0.68
    # 背景天空
    if is_rain:
        screen.fill(SKY_RAIN)
    elif is_night:
        screen.fill(SKY_NIGHT)
    else:
        screen.fill(SKY_DAY)
    # 季节草地底色
    pygame.draw.rect(screen, SEASON_COLOR[current_season], (grid_off_x, grid_off_y+grid_rows*grid_size, W, H))

    # 绘制左侧说明书（最先绘制，底层）
    draw_manual()

    # 事件处理
    for ev in pygame.event.get():
        if ev.type == pygame.QUIT:
            running = False
        # 鼠标点击操作土地
        if ev.type == pygame.MOUSEBUTTONDOWN and ev.button == 1:
            click = True
            p = get_click_plot(mx, my)
            if p is None:
                continue
            # 播种普通作物
            if selected_tool.startswith("seed_") and "apple" not in selected_tool:
                crop_key = selected_tool.replace("seed_","")
                if inventory_seed[crop_key] > 0 and p.crop_id is None and p.tree_id is None:
                    p.crop_id = crop_key
                    p.max_grow = CROP_DATA[crop_key]["grow_time"]
                    p.grow_progress = 0
                    inventory_seed[crop_key] -= 1
            # 种植果树
            elif selected_tool == "seed_apple":
                if inventory_seed["apple"]>0 and p.tree_id is None and p.crop_id is None:
                    p.tree_id = "apple"
                    p.max_grow = TREE_DATA["apple"]["grow_time"]
                    p.grow_progress = 0
                    inventory_seed["apple"] -=1
            # 浇水
            elif selected_tool == "water":
                add_wet = 5 + TOOL_LEVEL["water"] * 3
                p.is_wet = True
                p.wet_timer = add_wet
            # 收割
            elif selected_tool == "sickle":
                mul = 1 + TOOL_LEVEL["sickle"] * 0.4
                if p.crop_id and p.grow_progress >= p.max_grow:
                    earn = int(CROP_DATA[p.crop_id]["sell"] * mul)
                    gold += earn
                    warehouse[p.crop_id] = warehouse.get(p.crop_id, 0)+1
                    p.crop_id = None
                    p.grow_progress =0
                if p.tree_id and p.grow_progress >= p.max_grow:
                    earn = int(TREE_DATA[p.tree_id]["sell"]*mul)
                    gold += earn
                    p.grow_progress = 0
            # 喷雾除虫除草
            elif selected_tool == "spray":
                p.has_weed = False
                p.has_bug = False
        # 键盘快捷键
        if ev.type == pygame.KEYDOWN:
            # 工具切换
            if ev.key == pygame.K_1: selected_tool = "seed_wheat"
            elif ev.key == pygame.K_2: selected_tool = "seed_carrot"
            elif ev.key == pygame.K_3: selected_tool = "seed_tomato"
            elif ev.key == pygame.K_4: selected_tool = "seed_cabbage"
            elif ev.key == pygame.K_5: selected_tool = "seed_apple"
            elif ev.key == pygame.K_6: selected_tool = "water"
            elif ev.key == pygame.K_7: selected_tool = "sickle"
            elif ev.key == pygame.K_8: selected_tool = "spray"
            # M购买最便宜种子
            if ev.key == pygame.K_m:
                min_cost = 9999
                pick = None
                for k in CROP_DATA:
                    c = CROP_DATA[k]["seed_cost"]
                    if c < min_cost and gold >= c:
                        min_cost = c
                        pick = k
                if pick:
                    gold -= min_cost
                    inventory_seed[pick] +=1
            # T买果树苗
            if ev.key == pygame.K_t:
                c = TREE_DATA["apple"]["seed_cost"]
                if gold >= c:
                    gold -= c
                    inventory_seed["apple"] +=1
            # N买小鸡
            if ev.key == pygame.K_n:
                c = ANIMAL_DATA["chicken"]["buy_cost"]
                if gold >= c:
                    gold -= c
                    ax = random.randint(300, W-100)
                    ay = grid_off_y + grid_rows*grid_size + 40
                    animals.append([ax, ay, "chicken", 0])
            # U升级农具
            if ev.key == pygame.K_u:
                for tool in ["water","spray","sickle"]:
                    lv = TOOL_LEVEL[tool]
                    if lv < TOOL_MAX and gold >= UPGRADE_COST[lv]:
                        gold -= UPGRADE_COST[lv]
                        TOOL_LEVEL[tool] +=1
                        break
            # Z交付订单
            if ev.key == pygame.K_z and len(orders)>0:
                od = orders[0]
                have = warehouse.get(od["crop"],0)
                if have >= od["need"]:
                    gold += od["reward"]
                    warehouse[od["crop"]] -= od["need"]
                    orders.pop(0)
                    orders.append(create_order())

    # 成熟闪光渐变
    if flash_alpha > 0:
        flash_alpha -= 12
    else:
        # 检测成熟地块触发闪光
        for row in farm_plots:
            for p in row:
                if p.crop_id and p.grow_progress >= p.max_grow:
                    flash_alpha = 140
                    break

    # 农田全局逻辑更新
    for row in farm_plots:
        for p in row:
            # 湿润倒计时
            if p.wet_timer > 0:
                p.wet_timer -= dt
                if p.wet_timer <=0:
                    p.is_wet = False
            # 下雨自动全田湿润
            if is_rain:
                p.is_wet = True
                p.wet_timer = 6
            # 作物生长：湿润无杂草虫害才生长
            if p.crop_id and p.is_wet and not p.has_weed and not p.has_bug:
                p.grow_progress += dt
            if p.tree_id and p.is_wet:
                p.grow_progress += dt*0.4
            # 随机生成杂草虫害
            if random.random() < 0.0007:
                p.has_weed = True
            if random.random() < 0.0005:
                p.has_bug = True

    # 家畜生产鸡蛋计时
    for ani in animals:
        ani[3] += dt
        if ani[3] >= ANIMAL_DATA["chicken"]["produce_cycle"]:
            gold += ANIMAL_DATA["chicken"]["egg_price"]
            ani[3] = 0

    # 下雨雨滴下落更新
    if is_rain:
        for drop in rain_list:
            drop["y"] += drop["speed"]
            if drop["y"] > H:
                drop["y"] = random.randint(-H, 0)

    # 绘制所有地块
    for row in farm_plots:
        for p in row:
            draw_plot(p)
    # 家畜、雨水
    draw_animals()
    if is_rain:
        draw_rain()
    # 上层UI
    draw_shop()
    draw_order_panel()
    draw_toolbar()
    # 昼夜季节文字
    tip_day = font.render(f"第{day_count}天 | {current_season} {'雨夜' if is_rain else '夜晚' if is_night else '白天'}", True, WHITE)
    screen.blit(tip_day, (290, 20))

    pygame.display.update()
pygame.quit()