import pygame
import sys
import math

# 初始化 Pygame
pygame.init()

# 窗口设置
WIDTH, HEIGHT = 800, 650
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("👗 豆腐公主换装")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 50, 50)
DARK_RED = (200, 0, 0)
PINK = (255, 182, 193)
LIGHT_PINK = (255, 220, 225)
DARK_PINK = (255, 150, 180)
YELLOW = (255, 255, 100)
GOLD = (255, 215, 0)
ORANGE = (255, 165, 0)
GREEN = (50, 200, 50)
DARK_GREEN = (0, 150, 0)
BLUE = (50, 150, 255)
LIGHT_BLUE = (173, 216, 230)
PURPLE = (200, 50, 255)
BROWN = (139, 69, 19)
LIGHT_BROWN = (160, 120, 80)
GRAY = (150, 150, 150)
DARK_GRAY = (80, 80, 80)
LIGHT_GRAY = (200, 200, 200)
SKY_BLUE = (135, 206, 235)
SOFT_YELLOW = (255, 248, 220)
CREAM = (255, 253, 240)
TOFU_WHITE = (245, 240, 235)

# 帧率控制
clock = pygame.time.Clock()
FPS = 60

# 中文字体
def get_chinese_font(size):
    font_names = ["SimHei", "Microsoft YaHei", "PingFang SC", "Noto Sans CJK SC", "WenQuanYi Micro Hei", "Arial"]
    for name in font_names:
        try:
            return pygame.font.SysFont(name, size)
        except:
            continue
    return pygame.font.Font(None, size)

font = get_chinese_font(24)
small_font = get_chinese_font(16)
big_font = get_chinese_font(36)

# 服装部件类
class ClothingItem:
    def __init__(self, name, category, color, x, y, width, height, price=0, shape="rect"):
        self.name = name
        self.category = category  # "dress", "hair", "accessory", "shoes", "background"
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.price = price
        self.owned = False
        self.selected = False
        self.shape = shape  # "rect", "circle", "heart", "star"
        self.rotation = 0

    def draw(self, surface, preview=False):
        x, y = self.x, self.y
        w, h = self.width, self.height
        
        if preview:
            # 预览模式 - 显示在角色身上
            if self.category == "dress":
                # 裙子
                pygame.draw.ellipse(surface, self.color, (x, y, w, h))
                # 裙摆装饰
                for i in range(3):
                    dx = (i - 1) * 15
                    pygame.draw.arc(surface, self.lighten_color(0.3), 
                                  (x + dx, y + 5, w - 10, h - 10), 0, math.pi, 2)
            elif self.category == "hair":
                # 发型
                if self.name == "长发":
                    pygame.draw.ellipse(surface, self.color, (x - 10, y + 5, w + 20, h))
                    pygame.draw.ellipse(surface, self.lighten_color(0.2), 
                                      (x - 5, y + 10, w + 10, h - 5))
                elif self.name == "短发":
                    pygame.draw.arc(surface, self.color, (x - 5, y, w + 10, h), math.pi, 2*math.pi, 3)
                else:  # 双马尾
                    pygame.draw.ellipse(surface, self.color, (x - 15, y - 5, 12, h + 10))
                    pygame.draw.ellipse(surface, self.color, (x + w - 5, y - 5, 12, h + 10))
                    # 发饰
                    pygame.draw.circle(surface, PINK, (x - 10, y + 5), 4)
                    pygame.draw.circle(surface, PINK, (x + w - 2, y + 5), 4)
            elif self.category == "accessory":
                if self.shape == "heart":
                    points = []
                    for i in range(20):
                        t = i * 2 * math.pi / 20
                        px = x + w//2 + 8 * 16 * math.sin(t) ** 3
                        py = y + h//2 - (13 * math.cos(t) - 5 * math.cos(2*t) - 2 * math.cos(3*t) - math.cos(4*t))
                        points.append((px, py))
                    pygame.draw.polygon(surface, self.color, points)
                elif self.shape == "star":
                    points = []
                    for i in range(10):
                        angle = i * math.pi / 5 - math.pi / 2
                        r = w//2 if i % 2 == 0 else w//4
                        px = x + w//2 + r * math.cos(angle)
                        py = y + h//2 + r * math.sin(angle)
                        points.append((px, py))
                    pygame.draw.polygon(surface, self.color, points)
                else:
                    pygame.draw.circle(surface, self.color, (x + w//2, y + h//2), w//2)
            elif self.category == "shoes":
                pygame.draw.ellipse(surface, self.color, (x, y + h//2, w//2, h//2))
                pygame.draw.ellipse(surface, self.color, (x + w//2, y + h//2, w//2, h//2))
            elif self.category == "background":
                # 背景装饰
                if self.name == "花丛":
                    for i in range(5):
                        fx = x + 20 + i * 30
                        fy = y + 20 + math.sin(i) * 15
                        pygame.draw.circle(surface, self.color, (fx, fy), 8)
                        pygame.draw.circle(surface, YELLOW, (fx, fy), 3)
                elif self.name == "星星":
                    for i in range(6):
                        angle = i * math.pi / 3 + pygame.time.get_ticks() / 1000
                        px = x + w//2 + 30 * math.cos(angle)
                        py = y + h//2 + 30 * math.sin(angle)
                        points = []
                        for j in range(10):
                            a = j * math.pi / 5 - math.pi / 2 + angle
                            r = 8 if j % 2 == 0 else 4
                            sx = px + r * math.cos(a)
                            sy = py + r * math.sin(a)
                            points.append((sx, sy))
                        pygame.draw.polygon(surface, self.color, points)
        
        else:
            # 缩略图模式 - 显示在按钮中
            # 背景框
            pygame.draw.rect(surface, (240, 240, 240), (x, y, w, h), border_radius=8)
            pygame.draw.rect(surface, (200, 200, 200), (x, y, w, h), 2, border_radius=8)
            
            # 显示颜色预览
            preview_rect = pygame.Rect(x + 5, y + 5, w - 10, h - 30)
            pygame.draw.rect(surface, self.color, preview_rect, border_radius=5)
            
            # 名称
            name_text = small_font.render(self.name, True, BLACK)
            name_rect = name_text.get_rect(center=(x + w//2, y + h - 8))
            surface.blit(name_text, name_rect)
            
            # 拥有/选中标记
            if self.selected:
                pygame.draw.circle(surface, GREEN, (x + w - 12, y + 12), 8)
                pygame.draw.circle(surface, WHITE, (x + w - 12, y + 12), 4)
            elif self.owned:
                pygame.draw.circle(surface, BLUE, (x + w - 12, y + 12), 6)
            elif self.price > 0:
                price_text = small_font.render(f"💰{self.price}", True, GOLD)
                surface.blit(price_text, (x + 5, y + h - 25))
    
    def lighten_color(self, factor):
        r, g, b = self.color
        return (min(255, int(r + (255 - r) * factor)),
                min(255, int(g + (255 - g) * factor)),
                min(255, int(b + (255 - b) * factor)))

# 豆腐公主换装类
class DressUpGame:
    def __init__(self):
        self.player_x = 300
        self.player_y = 280
        self.player_size = 80
        
        # 当前装扮
        self.current_style = {
            "dress": None,
            "hair": None,
            "accessory": None,
            "shoes": None,
            "background": None,
        }
        
        # 装扮颜色
        self.base_color = TOFU_WHITE
        self.blush_color = LIGHT_PINK
        
        # 所有可用物品
        self.all_items = []
        self.create_items()
        
        # 当前选中的物品（用于购买/穿戴）
        self.selected_item = None
        
        # 金币
        self.money = 500
        
        # 提示信息
        self.message = ""
        self.message_timer = 0
        
        # 当前标签页
        self.current_category = "dress"
        self.categories = ["dress", "hair", "accessory", "shoes", "background"]
        self.category_names = {
            "dress": "👗 裙子",
            "hair": "💇 发型",
            "accessory": "💎 配饰",
            "shoes": "👠 鞋子",
            "background": "🎨 背景"
        }
        
        # 创建分类按钮
        self.category_buttons = []
        self.create_category_buttons()
        
        # 金币显示
        self.money_rect = pygame.Rect(WIDTH - 200, 20, 180, 40)
        
        # 点击位置（修复bug）
        self.click_pos = None
        self.mouth_happy = True
    
    def create_items(self):
        # 裙子
        dresses = [
            ("粉色公主裙", "dress", PINK, 0, 0, 60, 70, 0),
            ("蓝色晚礼服", "dress", LIGHT_BLUE, 0, 0, 60, 70, 100),
            ("金色华服", "dress", GOLD, 0, 0, 60, 70, 150),
            ("紫色优雅裙", "dress", PURPLE, 0, 0, 60, 70, 120),
            ("红色喜庆裙", "dress", RED, 0, 0, 60, 70, 100),
        ]
        
        # 发型
        hairs = [
            ("长发", "hair", BROWN, 0, 0, 40, 50, 0),
            ("短发", "hair", BROWN, 0, 0, 40, 40, 50),
            ("双马尾", "hair", (180, 100, 60), 0, 0, 40, 45, 80),
            ("金色长发", "hair", GOLD, 0, 0, 40, 50, 100),
            ("粉色短发", "hair", PINK, 0, 0, 40, 40, 80),
        ]
        
        # 配饰
        accessories = [
            ("皇冠", "accessory", GOLD, 0, 0, 30, 30, 0, "star"),
            ("爱心", "accessory", RED, 0, 0, 25, 25, 60, "heart"),
            ("花朵", "accessory", PINK, 0, 0, 25, 25, 50, "circle"),
            ("蝴蝶", "accessory", PURPLE, 0, 0, 30, 25, 80, "star"),
            ("月亮", "accessory", (200, 200, 100), 0, 0, 25, 25, 70, "circle"),
        ]
        
        # 鞋子
        shoes = [
            ("粉色鞋", "shoes", PINK, 0, 0, 40, 20, 0),
            ("蓝色鞋", "shoes", BLUE, 0, 0, 40, 20, 50),
            ("金色鞋", "shoes", GOLD, 0, 0, 40, 20, 80),
            ("红色鞋", "shoes", RED, 0, 0, 40, 20, 60),
        ]
        
        # 背景
        backgrounds = [
            ("花丛", "background", GREEN, 0, 0, 100, 60, 50),
            ("星星", "background", YELLOW, 0, 0, 100, 60, 80),
            ("彩虹", "background", (255, 200, 255), 0, 0, 100, 60, 100),
        ]
        
        # 合并所有物品
        all_items = dresses + hairs + accessories + shoes + backgrounds
        
        # 设置初始拥有状态（便宜的默认拥有）
        for item_data in all_items:
            price = item_data[6] if len(item_data) > 6 else 0
            item = ClothingItem(*item_data)
            if price == 0:
                item.owned = True
            self.all_items.append(item)
        
        # 默认穿戴一些物品
        for item in self.all_items:
            if item.category == "dress" and item.name == "粉色公主裙":
                self.current_style["dress"] = item
                item.selected = True
            elif item.category == "hair" and item.name == "长发":
                self.current_style["hair"] = item
                item.selected = True
            elif item.category == "accessory" and item.name == "皇冠":
                self.current_style["accessory"] = item
                item.selected = True
            elif item.category == "shoes" and item.name == "粉色鞋":
                self.current_style["shoes"] = item
                item.selected = True
    
    def create_category_buttons(self):
        self.category_buttons = []
        x = 20
        y = 80
        for cat in self.categories:
            rect = pygame.Rect(x, y, 90, 30)
            self.category_buttons.append((rect, cat, self.category_names[cat]))
            x += 100
    
    def draw_player(self, surface):
        cx, cy = self.player_x, self.player_y
        
        # 背景装饰
        if self.current_style["background"]:
            bg = self.current_style["background"]
            # 在角色后面绘制背景
            bg.x = cx - 60
            bg.y = cy - 40
            bg.width = 120
            bg.height = 100
            bg.draw(surface, preview=True)
        
        # 鞋子
        if self.current_style["shoes"]:
            shoe = self.current_style["shoes"]
            shoe.x = cx - 20
            shoe.y = cy + 30
            shoe.width = 40
            shoe.height = 20
            shoe.draw(surface, preview=True)
        else:
            # 默认鞋子（豆腐块底部）
            pygame.draw.ellipse(surface, (200, 180, 170), (cx - 20, cy + 30, 40, 15))
        
        # 身体（豆腐块）
        body_rect = pygame.Rect(cx - 25, cy - 20, 50, 55)
        pygame.draw.rect(surface, self.base_color, body_rect, border_radius=10)
        pygame.draw.rect(surface, (220, 215, 210), body_rect, 2, border_radius=10)
        
        # 豆腐纹理
        for i in range(3):
            px = cx - 15 + i * 15
            py = cy - 5 + (i % 2) * 15
            pygame.draw.circle(surface, (230, 225, 220), (px, py), 3)
        
        # 裙子
        if self.current_style["dress"]:
            dress = self.current_style["dress"]
            dress.x = cx - 30
            dress.y = cy + 5
            dress.width = 60
            dress.height = 50
            dress.draw(surface, preview=True)
        
        # 手臂（小豆腐块）
        arm_color = self.base_color
        for arm_x in [cx - 32, cx + 22]:
            pygame.draw.ellipse(surface, arm_color, (arm_x, cy, 12, 25))
            pygame.draw.ellipse(surface, (220, 215, 210), (arm_x, cy, 12, 25), 1)
        
        # 头发
        if self.current_style["hair"]:
            hair = self.current_style["hair"]
            hair.x = cx - 25
            hair.y = cy - 35
            hair.width = 50
            hair.height = 40
            hair.draw(surface, preview=True)
        
        # 头（圆形）
        head_radius = 25
        pygame.draw.circle(surface, self.base_color, (cx, cy - 25), head_radius)
        pygame.draw.circle(surface, (220, 215, 210), (cx, cy - 25), head_radius, 2)
        
        # 腮红
        for blush_x in [cx - 15, cx + 15]:
            blush_surf = pygame.Surface((12, 8), pygame.SRCALPHA)
            temp_surf = pygame.Surface((12, 8), pygame.SRCALPHA)
            pygame.draw.ellipse(temp_surf, (255, 180, 200), (0, 0, 12, 8))
            temp_surf.set_alpha(80)
            blush_surf.blit(temp_surf, (0, 0))
            surface.blit(blush_surf, (blush_x - 6, cy - 20))
        
        # 眼睛
        for eye_x in [cx - 10, cx + 10]:
            pygame.draw.circle(surface, BLACK, (eye_x, cy - 28), 4)
            pygame.draw.circle(surface, WHITE, (eye_x - 1, cy - 29), 2)
        
        # 嘴巴
        if self.mouth_happy:
            pygame.draw.arc(surface, BLACK, (cx - 10, cy - 22, 20, 12), 0, math.pi, 2)
        else:
            pygame.draw.arc(surface, BLACK, (cx - 8, cy - 18, 16, 10), math.pi, 2*math.pi, 2)
        
        # 配饰
        if self.current_style["accessory"]:
            acc = self.current_style["accessory"]
            acc.x = cx - 15
            acc.y = cy - 40
            acc.width = 30
            acc.height = 30
            acc.draw(surface, preview=True)
    
    def draw_ui(self, surface):
        # 标题
        title = big_font.render("👗 豆腐公主换装", True, DARK_RED)
        title_rect = title.get_rect(center=(WIDTH // 2, 30))
        surface.blit(title, title_rect)
        
        # 金钱
        money_bg = pygame.Rect(WIDTH - 200, 50, 180, 35)
        pygame.draw.rect(surface, GOLD, money_bg, border_radius=8)
        pygame.draw.rect(surface, DARK_GRAY, money_bg, 2, border_radius=8)
        money_text = font.render(f"💰 {self.money}", True, DARK_RED)
        money_rect = money_text.get_rect(center=(WIDTH - 110, 67))
        surface.blit(money_text, money_rect)
        
        # 分类标签
        for rect, cat, name in self.category_buttons:
            color = (200, 200, 255) if cat == self.current_category else (240, 240, 240)
            pygame.draw.rect(surface, color, rect, border_radius=6)
            pygame.draw.rect(surface, (180, 180, 180), rect, 2, border_radius=6)
            label = small_font.render(name, True, BLACK)
            label_rect = label.get_rect(center=(rect.x + rect.width // 2, rect.y + rect.height // 2))
            surface.blit(label, label_rect)
        
        # 显示当前分类的物品
        items_in_category = [item for item in self.all_items if item.category == self.current_category]
        
        # 网格布局
        start_x = 20
        start_y = 120
        cols = 4
        spacing_x = 110
        spacing_y = 120
        
        # 显示物品
        for i, item in enumerate(items_in_category):
            col = i % cols
            row = i // cols
            x = start_x + col * spacing_x
            y = start_y + row * spacing_y
            
            item.x = x
            item.y = y
            item.width = 80
            item.height = 90
            
            # 绘制物品
            item.draw(surface, preview=False)
            
            # 点击检测（修复bug - 使用click_pos）
            if self.click_pos:
                mouse_x, mouse_y = self.click_pos
                if (x <= mouse_x <= x + 80 and y <= mouse_y <= y + 90):
                    self.handle_item_click(item)
                    self.click_pos = None
        
        # 操作提示
        hint = small_font.render("点击物品穿戴/购买 | 已拥有的物品点击即可穿戴 | H键切换表情", True, DARK_GRAY)
        hint_rect = hint.get_rect(center=(WIDTH // 2, HEIGHT - 20))
        surface.blit(hint, hint_rect)
        
        # 提示信息
        if self.message_timer > 0:
            self.message_timer -= 1
            alpha = min(255, self.message_timer * 5)
            msg_surf = pygame.Surface((WIDTH, 40), pygame.SRCALPHA)
            msg_surf.fill((0, 0, 0, alpha * 0.6))
            surface.blit(msg_surf, (0, HEIGHT - 60))
            msg_text = font.render(self.message, True, WHITE)
            msg_rect = msg_text.get_rect(center=(WIDTH // 2, HEIGHT - 40))
            surface.blit(msg_text, msg_rect)
    
    def handle_item_click(self, item):
        if item.owned:
            # 已拥有，直接穿戴
            self.wear_item(item)
            self.message = f"✅ 已穿戴 {item.name}"
            self.message_timer = 60
        else:
            # 未拥有，尝试购买
            if self.money >= item.price:
                self.money -= item.price
                item.owned = True
                self.wear_item(item)
                self.message = f"🎉 购买成功！已穿戴 {item.name}"
                self.message_timer = 60
            else:
                self.message = f"❌ 金币不足！需要 {item.price} 金币"
                self.message_timer = 60
    
    def wear_item(self, item):
        # 取消同类别其他物品的选中状态
        for other in self.all_items:
            if other.category == item.category:
                other.selected = False
        
        # 穿戴该物品
        item.selected = True
        self.current_style[item.category] = item
    
    def handle_click(self, pos):
        mouse_x, mouse_y = pos
        
        # 检查分类按钮点击
        for rect, cat, _ in self.category_buttons:
            if rect.collidepoint(mouse_x, mouse_y):
                self.current_category = cat
                self.click_pos = None
                return True
        
        # 保存点击位置供draw_ui使用
        self.click_pos = pos
        return True

# 主游戏函数
def main():
    game = DressUpGame()
    running = True
    
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:  # 左键
                    game.handle_click(event.pos)
            
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_h:
                    game.mouth_happy = not game.mouth_happy
        
        # 绘制
        screen.fill(SKY_BLUE)
        
        # 绘制装饰背景（云朵）
        for i in range(3):
            cloud_x = 50 + i * 250
            cloud_y = 30 + i * 20
            pygame.draw.ellipse(screen, WHITE, (cloud_x, cloud_y, 80, 30))
            pygame.draw.ellipse(screen, WHITE, (cloud_x + 20, cloud_y - 10, 60, 30))
            pygame.draw.ellipse(screen, WHITE, (cloud_x + 40, cloud_y + 5, 50, 25))
        
        # 绘制角色
        game.draw_player(screen)
        
        # 绘制UI
        game.draw_ui(screen)
        
        # 绘制分隔线
        pygame.draw.line(screen, (180, 180, 180), (0, 110), (WIDTH, 110), 2)
        
        pygame.display.flip()
        clock.tick(FPS)
    
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()