import pygame
import sys
import random
import math
import json
import os

# 初始化Pygame
pygame.init()

# 屏幕设置
WINDOW_WIDTH = 1100
WINDOW_HEIGHT = 720
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("🏭 图形工厂")

# 颜色
COLORS = {
    'background': (25, 30, 45),
    'panel_bg': (40, 45, 65),
    'panel_border': (70, 80, 110),
    'text_light': (230, 235, 245),
    'text_gold': (255, 215, 0),
    'text_green': (100, 255, 100),
    'button_bg': (60, 100, 180),
    'button_hover': (80, 130, 210),
    'button_pressed': (40, 70, 140),
    'button_green': (60, 180, 80),
    'button_green_hover': (80, 210, 100),
    'button_red': (200, 60, 60),
    'button_red_hover': (230, 80, 80),
    'button_orange': (200, 140, 40),
    'button_orange_hover': (230, 170, 60),
}

# ========== 中文字体 ==========
def get_chinese_font(size):
    font_paths = [
        "C:/Windows/Fonts/simsun.ttc",
        "C:/Windows/Fonts/simhei.ttf",
        "C:/Windows/Fonts/msyh.ttc",
        "/System/Library/Fonts/PingFang.ttc",
        "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
    ]
    for path in font_paths:
        try:
            if os.path.exists(path):
                return pygame.font.Font(path, size)
        except:
            continue
    return pygame.font.Font(None, size)

FONT_TITLE = get_chinese_font(32)
FONT_LARGE = get_chinese_font(26)
FONT_MEDIUM = get_chinese_font(20)
FONT_SMALL = get_chinese_font(16)
FONT_TINY = get_chinese_font(12)

# ========== 图形数据 ==========
SHAPES = {
    'circle': {'name': '圆形', 'color': (255, 100, 100), 'cost': 5, 'exp': 5},
    'square': {'name': '方形', 'color': (100, 200, 255), 'cost': 8, 'exp': 8},
    'triangle': {'name': '三角形', 'color': (100, 255, 100), 'cost': 10, 'exp': 10},
    'star': {'name': '星形', 'color': (255, 215, 0), 'cost': 15, 'exp': 15},
    'diamond': {'name': '菱形', 'color': (255, 150, 255), 'cost': 20, 'exp': 20},
    'hexagon': {'name': '六边形', 'color': (100, 200, 200), 'cost': 25, 'exp': 25},
}

# ========== 产品配方 ==========
RECIPES = {
    '笑脸': {
        'shapes': ['circle', 'circle', 'circle'],
        'colors': [(255, 255, 200), (0, 0, 0), (0, 0, 0)],
        'value': 50,
        'exp': 40,
        'desc': '圆形 + 圆形 + 圆形'
    },
    '房子': {
        'shapes': ['square', 'triangle'],
        'colors': [(200, 180, 150), (200, 50, 50)],
        'value': 60,
        'exp': 50,
        'desc': '方形 + 三角形'
    },
    '钻石戒指': {
        'shapes': ['diamond', 'circle'],
        'colors': [(100, 200, 255), (255, 215, 0)],
        'value': 80,
        'exp': 60,
        'desc': '菱形 + 圆形'
    },
    '雪花': {
        'shapes': ['star', 'hexagon', 'star'],
        'colors': [(200, 230, 255), (150, 200, 255), (200, 230, 255)],
        'value': 100,
        'exp': 80,
        'desc': '星形 + 六边形 + 星形'
    },
    '魔法阵': {
        'shapes': ['circle', 'star', 'diamond', 'circle'],
        'colors': [(150, 100, 255), (255, 215, 0), (100, 200, 255), (150, 100, 255)],
        'value': 150,
        'exp': 120,
        'desc': '圆形 + 星形 + 菱形 + 圆形'
    },
    '图腾': {
        'shapes': ['triangle', 'square', 'triangle', 'square'],
        'colors': [(200, 100, 50), (150, 100, 50), (200, 100, 50), (150, 100, 50)],
        'value': 120,
        'exp': 100,
        'desc': '三角形 + 方形 + 三角形 + 方形'
    },
    '彩虹': {
        'shapes': ['circle', 'circle', 'circle', 'circle', 'circle'],
        'colors': [(255, 50, 50), (255, 150, 50), (255, 255, 50), (50, 255, 50), (50, 150, 255)],
        'value': 200,
        'exp': 150,
        'desc': '5个不同颜色的圆形'
    },
    '万花筒': {
        'shapes': ['circle', 'diamond', 'square', 'triangle'],
        'colors': [(255, 100, 200), (100, 200, 255), (255, 200, 100), (100, 255, 150)],
        'value': 250,
        'exp': 180,
        'desc': '圆形 + 菱形 + 方形 + 三角形'
    },
}

# ========== 升级数据 ==========
UPGRADES = {
    'speed': {
        'display_name': '生产效率',
        'base_cost': 50,
        'cost_multiplier': 1.5,
        'description': '生产速度 +15%',
        'max_level': 15,
        'attr_name': 'speed'
    },
    'quality': {
        'display_name': '产品质量',
        'base_cost': 80,
        'cost_multiplier': 1.6,
        'description': '产品价值 +12%',
        'max_level': 12,
        'attr_name': 'quality'
    },
    'automation': {
        'display_name': '自动化程度',
        'base_cost': 200,
        'cost_multiplier': 2.0,
        'description': '每秒自动生产 0.2 次',
        'max_level': 10,
        'attr_name': 'automation'
    },
    'storage': {
        'display_name': '仓储容量',
        'base_cost': 100,
        'cost_multiplier': 1.7,
        'description': '材料存储 +20%',
        'max_level': 10,
        'attr_name': 'storage'
    },
}

class Button:
    def __init__(self, x, y, width, height, text, color, text_color=None):
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.color = color
        self.text_color = text_color if text_color else COLORS['text_light']
        self.hover = False
        self.pressed = False
        self.visible = True
    
    def draw(self, surface):
        if not self.visible:
            return
        color = self.color
        if self.pressed:
            color = COLORS['button_pressed']
        elif self.hover:
            if self.color == COLORS['button_green']:
                color = COLORS['button_green_hover']
            elif self.color == COLORS['button_red']:
                color = COLORS['button_red_hover']
            elif self.color == COLORS['button_orange']:
                color = COLORS['button_orange_hover']
            else:
                color = COLORS['button_hover']
        
        pygame.draw.rect(surface, color, self.rect, border_radius=8)
        pygame.draw.rect(surface, COLORS['panel_border'], self.rect, 2, border_radius=8)
        
        text_surf = FONT_MEDIUM.render(self.text, True, self.text_color)
        text_rect = text_surf.get_rect(center=self.rect.center)
        surface.blit(text_surf, text_rect)
    
    def handle_event(self, event):
        if not self.visible:
            return False
        if event.type == pygame.MOUSEMOTION:
            self.hover = self.rect.collidepoint(event.pos)
            if not self.hover:
                self.pressed = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1 and self.rect.collidepoint(event.pos):
                self.pressed = True
                return True
        elif event.type == pygame.MOUSEBUTTONUP:
            if event.button == 1 and self.pressed:
                self.pressed = False
                if self.rect.collidepoint(event.pos):
                    return True
        return False

class ShapeObject:
    """图形对象"""
    def __init__(self, shape_type, color=None, size=30):
        self.type = shape_type
        self.color = color if color else SHAPES[shape_type]['color']
        self.size = size
        self.x = 0
        self.y = 0
    
    def draw(self, surface, x, y, size=None):
        s = size if size else self.size
        points = []
        
        if self.type == 'circle':
            pygame.draw.circle(surface, self.color, (int(x), int(y)), int(s))
            pygame.draw.circle(surface, (50, 50, 50), (int(x), int(y)), int(s), 1)
        
        elif self.type == 'square':
            rect = pygame.Rect(x - s/2, y - s/2, s, s)
            pygame.draw.rect(surface, self.color, rect)
            pygame.draw.rect(surface, (50, 50, 50), rect, 1)
        
        elif self.type == 'triangle':
            points = [
                (x, y - s * 0.8),
                (x - s * 0.7, y + s * 0.6),
                (x + s * 0.7, y + s * 0.6)
            ]
            pygame.draw.polygon(surface, self.color, points)
            pygame.draw.polygon(surface, (50, 50, 50), points, 1)
        
        elif self.type == 'star':
            for i in range(10):
                angle = math.radians(i * 36 - 90)
                r = s if i % 2 == 0 else s * 0.4
                px = x + math.cos(angle) * r
                py = y + math.sin(angle) * r
                points.append((px, py))
            pygame.draw.polygon(surface, self.color, points)
            pygame.draw.polygon(surface, (50, 50, 50), points, 1)
        
        elif self.type == 'diamond':
            points = [
                (x, y - s),
                (x + s * 0.7, y),
                (x, y + s),
                (x - s * 0.7, y)
            ]
            pygame.draw.polygon(surface, self.color, points)
            pygame.draw.polygon(surface, (50, 50, 50), points, 1)
        
        elif self.type == 'hexagon':
            for i in range(6):
                angle = math.radians(i * 60 - 30)
                px = x + math.cos(angle) * s
                py = y + math.sin(angle) * s
                points.append((px, py))
            pygame.draw.polygon(surface, self.color, points)
            pygame.draw.polygon(surface, (50, 50, 50), points, 1)

class CraftingSlot:
    """合成槽位"""
    def __init__(self, x, y, size=50):
        self.rect = pygame.Rect(x, y, size, size)
        self.shape = None
        self.color = None
    
    def draw(self, surface):
        pygame.draw.rect(surface, (50, 55, 80), self.rect, border_radius=5)
        pygame.draw.rect(surface, COLORS['panel_border'], self.rect, 2, border_radius=5)
        
        if self.shape:
            shape_obj = ShapeObject(self.shape, self.color, self.rect.width * 0.35)
            shape_obj.draw(surface, self.rect.centerx, self.rect.centery)
    
    def is_empty(self):
        return self.shape is None

class Product:
    """产品对象"""
    def __init__(self, recipe_name, shapes, colors):
        self.name = recipe_name
        self.shapes = shapes
        self.colors = colors
        self.data = RECIPES[recipe_name]
        self.x = 0
        self.y = 0
        self.angle = 0
        self.scale = 1.0
    
    def draw(self, surface, x, y, size=40):
        self.x = x
        self.y = y
        total = len(self.shapes)
        if total == 1:
            shape_obj = ShapeObject(self.shapes[0], self.colors[0], size * 0.8)
            shape_obj.draw(surface, x, y)
        elif total == 2:
            for i, (shape, color) in enumerate(zip(self.shapes, self.colors)):
                angle = math.radians(i * 180)
                px = x + math.cos(angle) * size * 0.5
                py = y + math.sin(angle) * size * 0.5
                shape_obj = ShapeObject(shape, color, size * 0.5)
                shape_obj.draw(surface, px, py)
        else:
            for i, (shape, color) in enumerate(zip(self.shapes, self.colors)):
                angle = math.radians(i * (360 / total))
                px = x + math.cos(angle) * size * 0.6
                py = y + math.sin(angle) * size * 0.6
                shape_obj = ShapeObject(shape, color, size * 0.4)
                shape_obj.draw(surface, px, py)

class ShapeFactory:
    """图形工厂主类"""
    def __init__(self):
        # 玩家数据
        self.gold = 100
        self.level = 1
        self.exp = 0
        self.exp_to_next = 80
        
        # 技能
        self.speed = 1.0
        self.quality = 1.0
        self.automation = 0.0
        self.storage = 1.0
        
        # 库存
        self.inventory = {shape: 0 for shape in SHAPES}
        self.max_inventory = 20
        
        # 合成槽
        self.slots = [CraftingSlot(380 + i * 70, 420, 55) for i in range(6)]
        
        # 当前合成选择
        self.selected_slot = None
        self.selected_shape = None
        
        # 产品列表
        self.products = []
        self.max_products = 10
        
        # 状态
        self.production_timer = 0
        self.production_interval = 60
        self.is_producing = False
        
        # 消息
        self.messages = []
        
        # 当前页面
        self.current_page = 'main'
        
        # ========== 按钮 ==========
        self.shop_tab = Button(50, 650, 120, 40, "🏪 商店", COLORS['button_bg'])
        self.stats_tab = Button(180, 650, 120, 40, "📊 统计", COLORS['button_bg'])
        self.back_button = Button(320, 650, 120, 40, "🔙 返回", COLORS['button_red'])
        self.back_button.visible = False
        
        self.produce_button = Button(50, 120, 120, 40, "⚙️ 生产", COLORS['button_green'])
        self.craft_button = Button(720, 460, 120, 50, "🔮 合成", COLORS['button_orange'])
        
        self.shape_buttons = {}
        self.init_shape_buttons()
        
        self.shop_buttons = {}
        self.init_shop_buttons()
        
        # 加载存档
        self.load_game()
        
        # 初始库存
        for shape in SHAPES:
            self.inventory[shape] = 3
    
    def init_shape_buttons(self):
        x = 50
        y = 180
        for shape, data in SHAPES.items():
            self.shape_buttons[shape] = {
                'button': Button(x, y, 90, 90, data['name'], data['color']),
                'shape': shape
            }
            x += 100
            if x > 350:
                x = 50
                y += 100
    
    def init_shop_buttons(self):
        y = 200
        for key, data in UPGRADES.items():
            self.shop_buttons[key] = {
                'button': Button(580, y, 180, 40, "升级", COLORS['button_bg']),
                'data': data,
                'key': key
            }
            y += 70
    
    def produce_shape(self):
        if self.is_producing:
            return
        
        total = sum(self.inventory.values())
        max_storage = int(self.max_inventory * (1 + self.storage * 0.2))
        if total >= max_storage:
            self.add_message("⚠️ 仓库已满!", COLORS['button_red'])
            return
        
        shape = random.choice(list(SHAPES.keys()))
        self.inventory[shape] += 1
        
        exp_gain = SHAPES[shape]['exp']
        self.exp += exp_gain
        
        self.add_message(f"🔨 生产了 {SHAPES[shape]['name']} +{exp_gain}经验")
        
        if self.exp >= self.exp_to_next:
            self.level_up()
        
        self.is_producing = True
        self.production_timer = 0
    
    def craft_product(self):
        if self.selected_slot is None:
            self.add_message("⚠️ 请先选择合成槽!", COLORS['button_red'])
            return
        
        slot = self.slots[self.selected_slot]
        if slot.is_empty():
            self.add_message("⚠️ 合成槽为空!", COLORS['button_red'])
            return
        
        slot_shapes = []
        slot_colors = []
        for s in self.slots:
            if not s.is_empty():
                slot_shapes.append(s.shape)
                slot_colors.append(s.color)
        
        matched_recipe = None
        for name, data in RECIPES.items():
            if len(data['shapes']) == len(slot_shapes):
                shapes_match = all(s == data['shapes'][i] for i, s in enumerate(slot_shapes))
                if shapes_match:
                    matched_recipe = name
                    break
        
        if not matched_recipe:
            self.add_message("❌ 没有匹配的配方!", COLORS['button_red'])
            return
        
        for s in self.slots:
            if not s.is_empty():
                self.inventory[s.shape] -= 1
                s.shape = None
                s.color = None
        
        data = RECIPES[matched_recipe]
        value = int(data['value'] * (1 + self.quality * 0.12))
        exp_gain = data['exp']
        
        self.gold += value
        self.exp += exp_gain
        
        product = Product(matched_recipe, data['shapes'], data['colors'])
        self.products.append(product)
        if len(self.products) > self.max_products:
            self.products.pop(0)
        
        self.add_message(f"🎉 合成 {matched_recipe}! +{value}💰 +{exp_gain}经验", COLORS['text_gold'])
        self.selected_slot = None
        
        if self.exp >= self.exp_to_next:
            self.level_up()
    
    def level_up(self):
        self.level += 1
        self.exp -= self.exp_to_next
        self.exp_to_next = int(self.exp_to_next * 1.15)
        reward = 30 + self.level * 10
        self.gold += reward
        self.add_message(f"🎉 升级! Lv.{self.level}! 奖励 {reward}💰", COLORS['text_gold'])
    
    def purchase_upgrade(self, key):
        data = UPGRADES[key]
        attr = data['attr_name']
        current = getattr(self, attr)
        if current >= data['max_level']:
            self.add_message(f"⚠️ {data['display_name']} 已满级!", COLORS['button_red'])
            return
        cost = int(data['base_cost'] * (data['cost_multiplier'] ** (current - 1)))
        if self.gold < cost:
            self.add_message(f"❌ 金币不足! 需要 {cost}💰", COLORS['button_red'])
            return
        self.gold -= cost
        setattr(self, attr, current + 1)
        self.add_message(f"✅ {data['display_name']} Lv.{current + 1}!", COLORS['button_green'])
        self.save_game()
    
    def add_message(self, text, color=COLORS['text_light']):
        self.messages.append({'text': text, 'color': color, 'time': 120})
        if len(self.messages) > 10:
            self.messages.pop(0)
    
    def go_to_page(self, page):
        self.current_page = page
        self.back_button.visible = (page != 'main')
    
    def update(self):
        if self.is_producing:
            self.production_timer += 1
            interval = int(self.production_interval / self.speed)
            if self.production_timer >= interval:
                self.is_producing = False
                self.production_timer = 0
        
        if self.automation > 0:
            if random.random() < self.automation / 60:
                self.produce_shape()
        
        for msg in self.messages:
            msg['time'] -= 1
        self.messages = [m for m in self.messages if m['time'] > 0]
    
    def save_game(self):
        """保存游戏数据"""
        try:
            # 保存产品名称列表（只保存名称，重新加载时重建）
            product_names = [p.name for p in self.products]
            
            # 保存合成槽状态
            slot_data = []
            for slot in self.slots:
                slot_data.append({
                    'shape': slot.shape,
                    'color': slot.color
                })
            
            save_data = {
                'gold': self.gold,
                'level': self.level,
                'exp': self.exp,
                'exp_to_next': self.exp_to_next,
                'speed': self.speed,
                'quality': self.quality,
                'automation': self.automation,
                'storage': self.storage,
                'inventory': self.inventory,
                'products': product_names,
                'slots': slot_data,
                'max_products': self.max_products,
            }
            with open('shape_factory_save.json', 'w', encoding='utf-8') as f:
                json.dump(save_data, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存失败: {e}")
    
    def load_game(self):
        """加载游戏数据"""
        try:
            if os.path.exists('shape_factory_save.json'):
                with open('shape_factory_save.json', 'r', encoding='utf-8') as f:
                    data = json.load(f)
                
                # 加载基本数据
                for key in ['gold', 'level', 'exp', 'exp_to_next', 'speed', 
                           'quality', 'automation', 'storage', 'max_products']:
                    if key in data:
                        setattr(self, key, data[key])
                
                # 加载库存
                if 'inventory' in data:
                    for shape, count in data['inventory'].items():
                        if shape in self.inventory:
                            self.inventory[shape] = count
                
                # 加载产品
                if 'products' in data:
                    self.products = []
                    for name in data['products']:
                        if name in RECIPES:
                            recipe = RECIPES[name]
                            product = Product(name, recipe['shapes'], recipe['colors'])
                            self.products.append(product)
                
                # 加载合成槽
                if 'slots' in data:
                    for i, slot_data in enumerate(data['slots']):
                        if i < len(self.slots):
                            self.slots[i].shape = slot_data.get('shape')
                            self.slots[i].color = slot_data.get('color')
                
                self.add_message("💾 游戏已加载!", COLORS['text_gold'])
        except Exception as e:
            print(f"加载失败: {e}")
    
    def draw(self, surface):
        surface.fill(COLORS['background'])
        
        self.draw_header(surface)
        
        if self.current_page == 'main':
            self.draw_main(surface)
        elif self.current_page == 'shop':
            self.draw_shop(surface)
        elif self.current_page == 'stats':
            self.draw_stats(surface)
        
        self.draw_navigation(surface)
        self.draw_messages(surface)
    
    def draw_header(self, surface):
        rect = pygame.Rect(0, 0, WINDOW_WIDTH, 70)
        pygame.draw.rect(surface, COLORS['panel_bg'], rect)
        pygame.draw.line(surface, COLORS['panel_border'], (0, 70), (WINDOW_WIDTH, 70), 2)
        
        surface.blit(FONT_LARGE.render(f"💰 {self.gold:,}", True, COLORS['text_gold']), (20, 18))
        surface.blit(FONT_MEDIUM.render(f"🏆 Lv.{self.level}", True, COLORS['text_light']), (220, 18))
        
        bar = pygame.Rect(220, 45, 200, 18)
        pygame.draw.rect(surface, (40, 40, 60), bar, border_radius=9)
        if self.exp_to_next > 0:
            prog = min(self.exp / self.exp_to_next, 1)
            fill = pygame.Rect(220, 45, int(200 * prog), 18)
            pygame.draw.rect(surface, COLORS['text_gold'], fill, border_radius=9)
        surface.blit(FONT_TINY.render(f"{self.exp}/{self.exp_to_next}", True, COLORS['text_light']), (225, 48))
        
        total = sum(self.inventory.values())
        max_s = int(self.max_inventory * (1 + self.storage * 0.2))
        surface.blit(FONT_MEDIUM.render(f"📦 {total}/{max_s}", True, COLORS['text_light']), (460, 20))
        surface.blit(FONT_MEDIUM.render(f"🎨 {len(self.products)}", True, COLORS['text_light']), (580, 20))
        
        if self.automation > 0:
            surface.blit(FONT_SMALL.render(f"🤖 {self.automation:.1f}/s", True, (100, 200, 255)), (660, 25))
    
    def draw_navigation(self, surface):
        rect = pygame.Rect(0, 640, WINDOW_WIDTH, 60)
        pygame.draw.rect(surface, COLORS['panel_bg'], rect)
        pygame.draw.line(surface, COLORS['panel_border'], (0, 640), (WINDOW_WIDTH, 640), 2)
        
        names = {'main': '🏭 工厂', 'shop': '🏪 商店', 'stats': '📊 统计'}
        surface.blit(FONT_MEDIUM.render(f"当前: {names.get(self.current_page, '')}", True, COLORS['text_gold']), (700, 652))
        self.shop_tab.draw(surface)
        self.stats_tab.draw(surface)
        self.back_button.draw(surface)
    
    def draw_main(self, surface):
        # 左侧面板
        panel = pygame.Rect(10, 90, 340, 350)
        pygame.draw.rect(surface, COLORS['panel_bg'], panel, border_radius=10)
        pygame.draw.rect(surface, COLORS['panel_border'], panel, 2, border_radius=10)
        surface.blit(FONT_MEDIUM.render("📐 选择图形", True, COLORS['text_light']), (20, 100))
        
        for key, data in self.shape_buttons.items():
            data['button'].draw(surface)
            count = self.inventory.get(key, 0)
            count_text = FONT_TINY.render(f"x{count}", True, COLORS['text_light'])
            surface.blit(count_text, (data['button'].rect.x + 65, data['button'].rect.y + 75))
        
        self.produce_button.draw(surface)
        if self.is_producing:
            prog = self.production_timer / (self.production_interval / self.speed)
            bar = pygame.Rect(50, 170, 90, 6)
            pygame.draw.rect(surface, (40, 40, 60), bar)
            pygame.draw.rect(surface, COLORS['text_gold'], pygame.Rect(50, 170, int(90 * prog), 6))
        
        # 中间面板
        panel = pygame.Rect(370, 90, 470, 400)
        pygame.draw.rect(surface, COLORS['panel_bg'], panel, border_radius=10)
        pygame.draw.rect(surface, COLORS['panel_border'], panel, 2, border_radius=10)
        surface.blit(FONT_MEDIUM.render("🔮 合成台", True, COLORS['text_light']), (380, 100))
        
        for i, slot in enumerate(self.slots):
            slot.draw(surface)
            if self.selected_slot == i:
                pygame.draw.rect(surface, COLORS['text_gold'], slot.rect, 3, border_radius=5)
        
        self.craft_button.draw(surface)
        
        surface.blit(FONT_SMALL.render("配方提示:", True, COLORS['text_light']), (380, 430))
        y = 455
        for name, data in list(RECIPES.items())[:4]:
            surface.blit(FONT_TINY.render(f"• {name}: {data['desc']}", True, (180, 180, 200)), (390, y))
            y += 20
        
        # 右侧面板
        panel = pygame.Rect(860, 90, 230, 400)
        pygame.draw.rect(surface, COLORS['panel_bg'], panel, border_radius=10)
        pygame.draw.rect(surface, COLORS['panel_border'], panel, 2, border_radius=10)
        surface.blit(FONT_MEDIUM.render("🎨 产品", True, COLORS['text_light']), (870, 100))
        
        y = 140
        for i, product in enumerate(self.products[-6:]):
            product.draw(surface, 930, y + 30, 35)
            name_text = FONT_TINY.render(product.name, True, COLORS['text_light'])
            surface.blit(name_text, (870, y + 55))
            y += 65
    
    def draw_shop(self, surface):
        rect = pygame.Rect(50, 90, 1000, 500)
        pygame.draw.rect(surface, COLORS['panel_bg'], rect, border_radius=15)
        pygame.draw.rect(surface, COLORS['panel_border'], rect, 2, border_radius=15)
        
        surface.blit(FONT_LARGE.render("🏪 商店 - 升级工厂!", True, COLORS['text_gold']), (70, 110))
        surface.blit(FONT_MEDIUM.render(f"💰 金币: {self.gold:,}", True, COLORS['text_light']), (70, 150))
        
        y = 200
        for key, data in self.shop_buttons.items():
            d = data['data']
            attr = d['attr_name']
            level = getattr(self, attr)
            max_lv = d['max_level']
            
            surface.blit(FONT_MEDIUM.render(f"{d['display_name']}: Lv.{level}/{max_lv}", True, COLORS['text_light']), (80, y))
            surface.blit(FONT_SMALL.render(d['description'], True, (180, 180, 200)), (80, y + 26))
            
            if level < max_lv:
                cost = int(d['base_cost'] * (d['cost_multiplier'] ** (level - 1)))
                surface.blit(FONT_SMALL.render(f"价格: {cost}💰", True, COLORS['text_gold']), (80, y + 46))
            else:
                surface.blit(FONT_SMALL.render("已满级! 🎉", True, COLORS['text_green']), (80, y + 46))
            
            data['button'].rect.y = y
            data['button'].draw(surface)
            y += 70
    
    def draw_stats(self, surface):
        rect = pygame.Rect(50, 90, 1000, 500)
        pygame.draw.rect(surface, COLORS['panel_bg'], rect, border_radius=15)
        pygame.draw.rect(surface, COLORS['panel_border'], rect, 2, border_radius=15)
        
        surface.blit(FONT_LARGE.render("📊 统计信息", True, COLORS['text_gold']), (70, 110))
        
        y = 160
        attrs = [
            (f"生产效率: {self.speed:.2f}x", COLORS['text_light']),
            (f"产品质量: +{self.quality*12:.0f}%", COLORS['text_gold']),
            (f"自动化: {self.automation:.1f}/s", (100, 200, 255)),
            (f"仓储容量: +{self.storage*20:.0f}%", COLORS['text_green']),
        ]
        for text, color in attrs:
            surface.blit(FONT_MEDIUM.render(text, True, color), (70, y))
            y += 32
        
        y += 10
        surface.blit(FONT_MEDIUM.render("📦 库存详情:", True, COLORS['text_light']), (70, y))
        y += 35
        
        x = 80
        for shape, count in self.inventory.items():
            if count > 0:
                color = SHAPES[shape]['color']
                text = f"{SHAPES[shape]['name']}: {count}"
                surface.blit(FONT_SMALL.render(text, True, color), (x, y))
                x += 140
                if x > 600:
                    x = 80
                    y += 28
        
        y += 40
        surface.blit(FONT_MEDIUM.render("🎨 已合成产品:", True, COLORS['text_light']), (70, y))
        y += 35
        
        if self.products:
            product_counts = {}
            for p in self.products:
                product_counts[p.name] = product_counts.get(p.name, 0) + 1
            
            x = 80
            for name, count in product_counts.items():
                surface.blit(FONT_SMALL.render(f"{name}: {count}", True, (180, 180, 200)), (x, y))
                x += 150
                if x > 600:
                    x = 80
                    y += 28
        else:
            surface.blit(FONT_SMALL.render("还没有合成任何产品...", True, (150, 150, 150)), (80, y))
    
    def draw_messages(self, surface):
        y = 680
        for msg in reversed(self.messages[-4:]):
            alpha = min(255, msg['time'] * 2)
            text = FONT_SMALL.render(msg['text'], True, msg['color'])
            text.set_alpha(alpha)
            surface.blit(text, (500, y))
            y -= 24

def main():
    clock = pygame.time.Clock()
    game = ShapeFactory()
    running = True
    
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game.save_game()
                running = False
            
            if game.produce_button.handle_event(event):
                if game.current_page == 'main':
                    game.produce_shape()
            
            if game.craft_button.handle_event(event):
                if game.current_page == 'main':
                    game.craft_product()
            
            if game.current_page == 'main':
                for key, data in game.shape_buttons.items():
                    if data['button'].handle_event(event):
                        for i, slot in enumerate(game.slots):
                            if slot.is_empty():
                                slot.shape = key
                                slot.color = SHAPES[key]['color']
                                game.selected_slot = i
                                break
                        else:
                            game.add_message("⚠️ 所有合成槽已满!", COLORS['button_red'])
                
                if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                    for i, slot in enumerate(game.slots):
                        if slot.rect.collidepoint(event.pos) and not slot.is_empty():
                            if game.selected_slot == i:
                                game.selected_slot = None
                            else:
                                game.selected_slot = i
                            break
            
            if game.shop_tab.handle_event(event):
                game.go_to_page('shop')
            if game.stats_tab.handle_event(event):
                game.go_to_page('stats')
            if game.back_button.handle_event(event):
                game.go_to_page('main')
            
            if game.current_page == 'shop':
                for key, data in game.shop_buttons.items():
                    if data['button'].handle_event(event):
                        game.purchase_upgrade(key)
        
        game.update()
        game.draw(screen)
        pygame.display.flip()
        clock.tick(60)
    
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()