import pygame
import sys

# 初始化
pygame.init()
W, H = 900, 700
screen = pygame.display.set_mode((W, H))
pygame.display.set_caption("农家乐种菜")
clock = pygame.time.Clock()
FPS = 60

# 颜色
WHITE = (255,255,255)
BLACK = (0,0,0)
BROWN = (125,82,45)
SKY = (130,200,240)
GOLD = (255,210,0)
RED = (220,20,20)
LIME = (150,240,150)

# 强制使用默认字体，不会崩溃
font_small = pygame.font.Font(None, 20)
font_mid = pygame.font.Font(None, 28)
font_big = pygame.font.Font(None, 38)

# 农田参数
CELL_SIZE = 120
OX, OY = 30, 110
COLS, ROWS = 6, 3

# 生长阶段
EMPTY, SEED, SEEDLING, RIPE = 0,1,2,3
# 工具
PLANT, WATER, HARVEST = 0,1,2

# 作物数据
crops = [
    {"name":"白菜","cost":10,"sell":30,"time":8,"color":(60,190,60)},
    {"name":"萝卜","cost":15,"sell":45,"time":12,"color":(220,40,40)},
    {"name":"玉米","cost":25,"sell":70,"time":18,"color":(235,200,20)}
]

class Farm:
    def __init__(self):
        self.money = 100
        self.tool = PLANT
        self.select_crop = 0
        self.shop = False
        # 地块初始化
        self.land = []
        for y in range(ROWS):
            row = []
            for x in range(COLS):
                row.append({"s":EMPTY,"cid":-1,"t":0,"wet":False})
            self.land.append(row)

    def text(self, txt, x, y, col=BLACK, fnt=font_mid):
        surf = fnt.render(txt, True, col)
        screen.blit(surf, (x,y))

    def draw_top(self):
        pygame.draw.rect(screen, SKY, (0,0,W,100))
        self.text(f"金币:{self.money}",15,18,GOLD,font_big)
        self.text("1播种 2浇水 3收割 | S商店 ESC关闭商店", 270,25,WHITE,font_small)
        # 工具按钮
        tools = ["播种","浇水","收割"]
        for i in range(3):
            x = 15 + i*130
            if self.tool == i:
                pygame.draw.rect(screen,GOLD,(x,60,110,32))
            else:
                pygame.draw.rect(screen,WHITE,(x,60,110,32))
            pygame.draw.rect(screen,BLACK,(x,60,110,32),2)
            self.text(tools[i], x+35,65)

    def draw_field(self):
        for ry in range(ROWS):
            for rx in range(COLS):
                x = OX + rx*CELL_SIZE
                y = OY + ry*CELL_SIZE
                cell = self.land[ry][rx]
                # 土地
                pygame.draw.rect(screen,BROWN,(x,y,CELL_SIZE-6,CELL_SIZE-6))
                pygame.draw.rect(screen,BLACK,(x,y,CELL_SIZE-6,CELL_SIZE-6),2)
                if cell["s"] == EMPTY:
                    continue
                cr = crops[cell["cid"]]
                # 种子
                if cell["s"] == SEED:
                    pygame.draw.circle(screen,BLACK,(x+55,y+60),9)
                    if not cell["wet"]:
                        self.text("需浇水",x+20,y+92,RED,font_small)
                # 幼苗
                elif cell["s"] == SEEDLING:
                    pygame.draw.circle(screen,cr["color"],(x+55,y+50),22)
                    self.text(f"{int(cell['t'])}/{cr['time']}",x+30,y+90,WHITE,font_small)
                # 成熟
                elif cell["s"] == RIPE:
                    pygame.draw.circle(screen,cr["color"],(x+55,y+45),36)
                    pygame.draw.circle(screen,GOLD,(x+55,y+45),40,3)
                    self.text("可收割",x+25,y+90,GOLD,font_small)

    def draw_shop(self):
        if not self.shop:
            return
        # 遮罩
        mask = pygame.Surface((W,H), pygame.SRCALPHA)
        mask.fill((0,0,0,160))
        screen.blit(mask,(0,0))
        # 商店框
        sw,sh = 520,380
        sx,sy = (W-sw)//2, (H-sh)//2
        pygame.draw.rect(screen,WHITE,(sx,sy,sw,sh))
        pygame.draw.rect(screen,BLACK,(sx,sy,sw,sh),3)
        self.text("种子商店", sx+40, sy+12, BLACK, font_big)
        # 商品
        for i,c in enumerate(crops):
            cy = sy + 70 + i*80
            if self.select_crop == i:
                pygame.draw.rect(screen,LIME,(sx+20,cy,sw-40,70))
            pygame.draw.rect(screen,GRAY,(sx+20,cy,sw-40,70),2)
            self.text(f"{c['name']} 买入{c['cost']} 卖出{c['sell']}", sx+40, cy+8)
            self.text(f"成熟时间:{c['time']}秒", sx+40, cy+40, (20,140,20), font_small)

    def click_land(self,mx,my):
        for ry in range(ROWS):
            for rx in range(COLS):
                x = OX + rx*CELL_SIZE
                y = OY + ry*CELL_SIZE
                r = pygame.Rect(x,y,CELL_SIZE-6,CELL_SIZE-6)
                if r.collidepoint(mx,my):
                    cell = self.land[ry][rx]
                    if self.tool == PLANT:
                        if cell["s"] == EMPTY and self.money >= crops[self.select_crop]["cost"]:
                            self.money -= crops[self.select_crop]["cost"]
                            cell["s"] = SEED
                            cell["cid"] = self.select_crop
                            cell["t"] = 0
                            cell["wet"] = False
                    elif self.tool == WATER:
                        if cell["s"] == SEED and not cell["wet"]:
                            cell["wet"] = True
                    elif self.tool == HARVEST:
                        if cell["s"] == RIPE:
                            self.money += crops[cell["cid"]]["sell"]
                            cell["s"] = EMPTY
                            cell["cid"] = -1
                            cell["t"] = 0
                    return

    def click_shop_item(self,mx,my):
        sw,sh = 520,380
        sx,sy = (W-sw)//2, (H-sh)//2
        for i in range(len(crops)):
            cy = sy + 70 + i*80
            rect = pygame.Rect(sx+20, cy, sw-40,70)
            if rect.collidepoint(mx,my):
                self.select_crop = i

    def update_grow(self,dt):
        for row in self.land:
            for cell in row:
                if cell["s"] == SEED and cell["wet"]:
                    cell["s"] = SEEDLING
                elif cell["s"] == SEEDLING:
                    cell["t"] += dt
                    if cell["t"] >= crops[cell["cid"]]["time"]:
                        cell["s"] = RIPE

    def render(self):
        screen.fill(SKY)
        self.draw_top()
        self.draw_field()
        self.draw_shop()

def main():
    game = Farm()
    last = pygame.time.get_ticks() / 1000
    run = True
    while run:
        now = pygame.time.get_ticks() / 1000
        delta = now - last
        last = now

        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                run = False
            if e.type == pygame.MOUSEBUTTONDOWN and e.button == 1:
                mx,my = e.pos
                if game.shop:
                    game.click_shop_item(mx,my)
                else:
                    game.click_land(mx,my)
            if e.type == pygame.KEYDOWN:
                if e.key == pygame.K_1:
                    game.tool = PLANT
                elif e.key == pygame.K_2:
                    game.tool = WATER
                elif e.key == pygame.K_3:
                    game.tool = HARVEST
                elif e.key == pygame.K_s:
                    game.shop = not game.shop
                elif e.key == pygame.K_ESCAPE:
                    game.shop = False

        game.update_grow(delta)
        game.render()
        pygame.display.flip()
        clock.tick(FPS)
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()