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

# 初始化Pygame
pygame.init()

# 屏幕设置
WINDOW_WIDTH = 1000
WINDOW_HEIGHT = 700
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("🎣 捕鱼模拟器")

# 颜色
COLORS = {
    'background': (20, 40, 70),
    'panel_bg': (30, 50, 80),
    'panel_border': (80, 120, 180),
    'text_light': (240, 240, 240),
    'text_gold': (255, 215, 0),
    '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),
    'seaweed': (40, 120, 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_LARGE = get_chinese_font(28)
FONT_MEDIUM = get_chinese_font(22)
FONT_SMALL = get_chinese_font(18)
FONT_TINY = get_chinese_font(14)

# ========== 鱼类数据 ==========
FISH_TYPES = {
    '小丑鱼': {'color': (255, 150, 50), 'size': 20, 'speed': 1.5, 'value': 10, 'exp': 15, 'chance': 0.25},
    '河豚': {'color': (100, 200, 100), 'size': 25, 'speed': 1.0, 'value': 20, 'exp': 25, 'chance': 0.20},
    '金鱼': {'color': (255, 200, 50), 'size': 18, 'speed': 2.0, 'value': 15, 'exp': 20, 'chance': 0.18},
    '三文鱼': {'color': (255, 120, 120), 'size': 30, 'speed': 2.5, 'value': 35, 'exp': 40, 'chance': 0.15},
    '石斑鱼': {'color': (150, 100, 80), 'size': 35, 'speed': 1.2, 'value': 50, 'exp': 55, 'chance': 0.10},
    '金枪鱼': {'color': (100, 150, 200), 'size': 40, 'speed': 3.0, 'value': 80, 'exp': 80, 'chance': 0.06},
    '蓝鳍鱼': {'color': (50, 100, 200), 'size': 45, 'speed': 2.8, 'value': 150, 'exp': 130, 'chance': 0.04},
    '金龙鱼': {'color': (255, 215, 0), 'size': 50, 'speed': 1.8, 'value': 300, 'exp': 250, 'chance': 0.02},
}

UPGRADES = {
    'net_size': {
        'display_name': '渔网大小',
        'base_cost': 50,
        'cost_multiplier': 1.6,
        'description': '捕鱼范围 +10%',
        'max_level': 15,
        'attr_name': 'net_size'
    },
    'fishing_speed': {
        'display_name': '抛网速度',
        'base_cost': 40,
        'cost_multiplier': 1.5,
        'description': '冷却时间 -8%',
        'max_level': 12,
        'attr_name': 'fishing_speed'
    },
    'luck': {
        'display_name': '幸运值',
        'base_cost': 100,
        'cost_multiplier': 1.8,
        'description': '稀有鱼概率 +4%',
        'max_level': 10,
        'attr_name': 'luck'
    },
    'auto_fish': {
        'display_name': '自动捕鱼',
        'base_cost': 300,
        'cost_multiplier': 2.2,
        'description': '每秒自动抛网 0.3 次',
        'max_level': 8,
        'attr_name': 'auto_fish'
    },
}

class Button:
    def __init__(self, x, y, width, height, text, color):
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.color = color
        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']
            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, COLORS['text_light'])
        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 Fish:
    def __init__(self, fish_type):
        self.type = fish_type
        self.data = FISH_TYPES[fish_type]
        self.x = random.randint(80, WINDOW_WIDTH - 80)
        self.y = random.randint(100, WINDOW_HEIGHT - 150)
        self.angle = random.uniform(0, 2 * math.pi)
        self.speed = self.data['speed'] * random.uniform(0.7, 1.3)
        self.turn_timer = random.randint(60, 180)
        self.size = self.data['size'] * random.uniform(0.8, 1.2)
        self.tail_angle = 0
        self.tail_speed = random.uniform(0.05, 0.1)
        self.alive = True
        self.caught = False
        self.caught_timer = 0
    
    def update(self):
        if self.caught:
            self.caught_timer += 1
            if self.caught_timer > 30:
                self.alive = False
            return
        
        self.turn_timer -= 1
        if self.turn_timer <= 0:
            self.angle += random.uniform(-1.5, 1.5)
            self.turn_timer = random.randint(60, 180)
            self.speed = self.data['speed'] * random.uniform(0.7, 1.3)
        
        margin = 50
        if self.x < margin:
            self.angle = random.uniform(-math.pi/2, math.pi/2)
        elif self.x > WINDOW_WIDTH - margin:
            self.angle = random.uniform(math.pi/2, 3*math.pi/2)
        if self.y < 80:
            self.angle = random.uniform(0, math.pi)
        elif self.y > WINDOW_HEIGHT - 100:
            self.angle = random.uniform(math.pi, 2*math.pi)
        
        self.x += math.cos(self.angle) * self.speed
        self.y += math.sin(self.angle) * self.speed
        self.tail_angle += self.tail_speed
    
    def draw(self, surface):
        if not self.alive:
            return
        
        color = self.data['color']
        size = self.size
        
        # 鱼身
        points = []
        for i in range(16):
            t = i / 16 * 2 * math.pi
            px = self.x + math.cos(t) * size * 1.4
            py = self.y + math.sin(t) * size
            points.append((px, py))
        
        rotated = []
        for px, py in points:
            dx, dy = px - self.x, py - self.y
            rx = dx * math.cos(-self.angle) - dy * math.sin(-self.angle) + self.x
            ry = dx * math.sin(-self.angle) + dy * math.cos(-self.angle) + self.y
            rotated.append((rx, ry))
        
        pygame.draw.polygon(surface, color, rotated)
        pygame.draw.polygon(surface, (50, 50, 50), rotated, 1)
        
        # 尾巴
        tx = self.x - math.cos(self.angle) * size * 1.2
        ty = self.y - math.sin(self.angle) * size * 1.2
        ts = size * 0.6
        tail = [
            (tx, ty),
            (tx - math.cos(self.angle + math.pi/4 + self.tail_angle) * ts,
             ty - math.sin(self.angle + math.pi/4 + self.tail_angle) * ts),
            (tx - math.cos(self.angle - math.pi/4 + self.tail_angle) * ts,
             ty - math.sin(self.angle - math.pi/4 + self.tail_angle) * ts),
        ]
        pygame.draw.polygon(surface, color, tail)
        
        # 眼睛
        ex = self.x + math.cos(self.angle) * size * 0.5
        ey = self.y + math.sin(self.angle) * size * 0.4
        pygame.draw.circle(surface, (255, 255, 255), (int(ex), int(ey)), size * 0.2)
        pygame.draw.circle(surface, (0, 0, 0), (int(ex + math.cos(self.angle) * size * 0.1),
                                                int(ey + math.sin(self.angle) * size * 0.1)), size * 0.08)
    
    def get_rect(self):
        return pygame.Rect(self.x - self.size, self.y - self.size, self.size * 2, self.size * 2)

class Net:
    def __init__(self, x, y, size):
        self.x = x
        self.y = y
        self.size = size
        self.radius = 10
        self.max_radius = size
        self.expanding = True
        self.finished = False
        self.life = 40
    
    def update(self):
        if self.expanding:
            self.radius += 4
            if self.radius >= self.max_radius:
                self.expanding = False
                self.finished = True
    
    def draw(self, surface):
        if self.finished:
            return
        # 外圈
        alpha = int(150 * (1 - self.radius / self.max_radius * 0.5))
        for r in range(0, int(self.radius), 10):
            pygame.draw.circle(surface, (200, 220, 255, alpha // 2), 
                             (int(self.x), int(self.y)), r, 1)
        pygame.draw.circle(surface, (200, 220, 255, alpha), 
                         (int(self.x), int(self.y)), int(self.radius), 2)
        # 十字线
        for angle in [0, math.pi/2, math.pi, 3*math.pi/2]:
            ex = self.x + math.cos(angle) * self.radius
            ey = self.y + math.sin(angle) * self.radius
            pygame.draw.line(surface, (200, 220, 255, alpha // 2), 
                           (self.x, self.y), (ex, ey), 1)
    
    def check_collision(self, fish):
        if self.finished:
            return False
        dx = fish.x - self.x
        dy = fish.y - self.y
        return math.sqrt(dx*dx + dy*dy) < self.radius + fish.size * 0.5

class FishingSimulator:
    def __init__(self):
        # 玩家数据
        self.gold = 0
        self.level = 1
        self.exp = 0
        self.exp_to_next = 100
        self.total_caught = 0
        self.total_value = 0
        
        # 技能
        self.net_size = 1.0
        self.fishing_speed = 1.0
        self.luck = 0.0
        self.auto_fish = 0.0
        
        # 状态
        self.fish_list = []
        self.nets = []
        self.is_fishing = False
        self.cooldown = 0
        self.cooldown_max = 60
        self.fish_stats = {fish: 0 for fish in FISH_TYPES}
        self.bubbles = []
        self.messages = []
        self.current_page = 'main'
        self.mouse_pos = (0, 0)
        
        # 按钮
        self.fish_button = Button(400, 500, 200, 60, "🎣 撒网!", COLORS['button_green'])
        self.shop_tab = Button(50, 620, 120, 40, "🏪 商店", COLORS['button_bg'])
        self.stats_tab = Button(180, 620, 120, 40, "📊 统计", COLORS['button_bg'])
        self.back_button = Button(320, 620, 120, 40, "🔙 返回", COLORS['button_red'])
        self.back_button.visible = False
        
        self.shop_buttons = {}
        self.init_shop_buttons()
        
        # 生成初始鱼群
        for _ in range(20):
            self.spawn_fish()
        
        self.load_game()
    
    def init_shop_buttons(self):
        y_pos = 200
        for key, data in UPGRADES.items():
            self.shop_buttons[key] = {
                'button': Button(580, y_pos, 180, 40, "升级", COLORS['button_bg']),
                'data': data,
                'key': key
            }
            y_pos += 75
    
    def spawn_fish(self):
        fish_types = list(FISH_TYPES.keys())
        weights = [FISH_TYPES[f]['chance'] for f in fish_types]
        # 应用幸运
        weights = [w * (1 + self.luck * 0.3) for w in weights]
        total = sum(weights)
        weights = [w / total for w in weights]
        selected = random.choices(fish_types, weights=weights)[0]
        fish = Fish(selected)
        # 限制深度
        if selected in ['小丑鱼', '河豚', '金鱼']:
            fish.y = random.randint(100, 300)
        elif selected in ['三文鱼', '石斑鱼']:
            fish.y = random.randint(250, 450)
        else:
            fish.y = random.randint(400, 580)
        self.fish_list.append(fish)
    
    def cast_net(self, x, y):
        if self.is_fishing or self.cooldown > 0:
            return
        self.is_fishing = True
        net_radius = 60 + self.net_size * 20
        net = Net(x, y, net_radius)
        self.nets.append(net)
        
        base = self.cooldown_max
        reduced = base * (1 - (self.fishing_speed - 1) * 0.08)
        self.cooldown = max(20, int(reduced))
        
        # 检查捕获
        caught = []
        for fish in self.fish_list:
            if not fish.alive or fish.caught:
                continue
            if net.check_collision(fish):
                caught.append(fish)
                fish.caught = True
        
        if caught:
            total_val = 0
            total_exp = 0
            for fish in caught:
                data = FISH_TYPES[fish.type]
                val = int(data['value'] * (1 + self.net_size * 0.05))
                if random.random() < self.luck * 0.1:
                    val = int(val * 1.5)
                self.gold += val
                self.exp += data['exp']
                self.total_caught += 1
                self.total_value += val
                total_val += val
                total_exp += data['exp']
                self.fish_stats[fish.type] += 1
                
                # 气泡
                for _ in range(10):
                    angle = random.uniform(0, 2 * math.pi)
                    speed = random.uniform(1, 4)
                    self.bubbles.append({
                        'x': fish.x, 'y': fish.y,
                        'vx': math.cos(angle) * speed,
                        'vy': math.sin(angle) * speed - 2,
                        'size': random.randint(3, 7),
                        'life': 30
                    })
            
            self.add_message(f"🎣 捕获 {len(caught)} 条鱼! +{total_val}💰 +{total_exp}经验")
            
            if self.exp >= self.exp_to_next:
                self.level_up()
        
        self.is_fishing = False
    
    def level_up(self):
        self.level += 1
        self.exp -= self.exp_to_next
        self.exp_to_next = int(self.exp_to_next * 1.2)
        reward = 50 + self.level * 10
        self.gold += reward
        self.add_message(f"🎉 升级! Lv.{self.level}! 奖励 {reward}💰", COLORS['text_gold'])
    
    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 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 go_to_page(self, page):
        self.current_page = page
        self.back_button.visible = (page != 'main')
    
    def update(self):
        # 更新鱼
        for fish in self.fish_list[:]:
            fish.update()
            if not fish.alive:
                self.fish_list.remove(fish)
        
        # 补充鱼群
        target = 15 + self.level
        while len(self.fish_list) < target:
            self.spawn_fish()
        
        # 更新渔网
        for net in self.nets[:]:
            net.update()
            if net.finished:
                self.nets.remove(net)
        
        # 冷却
        if self.cooldown > 0:
            self.cooldown -= 1
        
        # 自动捕鱼
        if self.auto_fish > 0 and not self.is_fishing and self.cooldown == 0:
            if random.random() < self.auto_fish / 60:
                x = random.randint(100, WINDOW_WIDTH - 100)
                y = random.randint(120, WINDOW_HEIGHT - 150)
                self.cast_net(x, y)
        
        # 气泡
        for b in self.bubbles[:]:
            b['x'] += b['vx']
            b['y'] += b['vy']
            b['vy'] += 0.08
            b['life'] -= 1
            if b['life'] <= 0:
                self.bubbles.remove(b)
        
        # 消息
        for msg in self.messages:
            msg['time'] -= 1
        self.messages = [m for m in self.messages if m['time'] > 0]
    
    def draw(self, surface):
        # 水面
        for y in range(WINDOW_HEIGHT):
            prog = y / WINDOW_HEIGHT
            r = int(20 + prog * 15)
            g = int(40 + prog * 50)
            b = int(70 + prog * 80)
            pygame.draw.line(surface, (r, g, b), (0, y), (WINDOW_WIDTH, y))
        
        # 水草
        for x in range(40, WINDOW_WIDTH, 100):
            h = random.randint(40, 70)
            pts = [(x + random.randint(-5, 5), WINDOW_HEIGHT - 20),
                   (x + random.randint(-15, 15), WINDOW_HEIGHT - 20 - h * 0.5),
                   (x + random.randint(-10, 10), WINDOW_HEIGHT - 20 - h)]
            pygame.draw.lines(surface, COLORS['seaweed'], False, pts, 3)
        
        # 鱼
        for fish in self.fish_list:
            if not fish.caught:
                fish.draw(surface)
        
        # 捕获闪烁
        for fish in self.fish_list:
            if fish.caught and fish.alive and fish.caught_timer % 4 < 2:
                fish.draw(surface)
        
        # 渔网
        for net in self.nets:
            net.draw(surface)
        
        # 气泡
        for b in self.bubbles:
            alpha = int(150 * b['life'] / 30)
            pygame.draw.circle(surface, (200, 230, 255, alpha),
                             (int(b['x']), int(b['y'])), int(b['size'] * b['life'] / 30))
        
        # 顶部信息
        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)
        
        # 消息
        y = 650
        for msg in reversed(self.messages[-5:]):
            alpha = min(255, msg['time'] * 2)
            text = FONT_SMALL.render(msg['text'], True, msg['color'])
            text.set_alpha(alpha)
            surface.blit(text, (20, y))
            y -= 24
    
    def draw_header(self, surface):
        rect = pygame.Rect(0, 0, WINDOW_WIDTH, 70)
        pygame.draw.rect(surface, (30, 50, 80), rect)
        pygame.draw.line(surface, (80, 120, 180), (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']), (250, 18))
        
        # 经验条
        bar = pygame.Rect(250, 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(250, 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']), (255, 48))
        
        surface.blit(FONT_MEDIUM.render(f"🐟 {self.total_caught}", True, COLORS['text_light']), (500, 20))
        if self.auto_fish > 0:
            surface.blit(FONT_SMALL.render(f"🤖 {self.auto_fish:.1f}/s", True, (100, 200, 255)), (620, 25))
    
    def draw_navigation(self, surface):
        rect = pygame.Rect(0, 610, WINDOW_WIDTH, 60)
        pygame.draw.rect(surface, (30, 50, 80), rect)
        pygame.draw.line(surface, (80, 120, 180), (0, 610), (WINDOW_WIDTH, 610), 2)
        
        names = {'main': '🎣 捕鱼', 'shop': '🏪 商店', 'stats': '📊 统计'}
        surface.blit(FONT_MEDIUM.render(f"当前: {names.get(self.current_page, '')}", True, COLORS['text_gold']), (700, 622))
        self.shop_tab.draw(surface)
        self.stats_tab.draw(surface)
        self.back_button.draw(surface)
    
    def draw_main(self, surface):
        alive = len([f for f in self.fish_list if not f.caught])
        surface.blit(FONT_SMALL.render(f"🐟 鱼群: {alive}", True, COLORS['text_light']), (50, 90))
        if self.cooldown > 0:
            surface.blit(FONT_SMALL.render(f"⏳ 冷却: {self.cooldown//10 + 1}s", True, (200, 200, 200)), (50, 115))
        
        self.fish_button.draw(surface)
        
        # 瞄准
        if not self.is_fishing and self.cooldown == 0:
            x, y = self.mouse_pos
            r = 60 + self.net_size * 20
            pygame.draw.circle(surface, (200, 220, 255, 30), (x, y), int(r), 1)
            pygame.draw.circle(surface, (200, 220, 255, 15), (x, y), int(r * 0.5), 1)
    
    def draw_shop(self, surface):
        rect = pygame.Rect(50, 90, 900, 470)
        pygame.draw.rect(surface, (30, 50, 80), rect, border_radius=15)
        pygame.draw.rect(surface, (80, 120, 180), 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 + 28))
            
            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 + 50))
            else:
                surface.blit(FONT_SMALL.render("已满级! 🎉", True, (100, 255, 100)), (80, y + 50))
            
            data['button'].rect.y = y
            data['button'].draw(surface)
            y += 75
    
    def draw_stats(self, surface):
        rect = pygame.Rect(50, 90, 900, 470)
        pygame.draw.rect(surface, (30, 50, 80), rect, border_radius=15)
        pygame.draw.rect(surface, (80, 120, 180), rect, 2, border_radius=15)
        
        surface.blit(FONT_LARGE.render("📊 统计信息", True, COLORS['text_gold']), (70, 110))
        surface.blit(FONT_MEDIUM.render(f"总捕获: {self.total_caught} 条", True, COLORS['text_light']), (70, 150))
        surface.blit(FONT_MEDIUM.render(f"总收益: {self.total_value:,} 💰", True, COLORS['text_gold']), (70, 185))
        
        # 属性
        y = 230
        attrs = [
            (f"渔网大小: Lv.{self.net_size}", COLORS['text_light']),
            (f"抛网速度: {self.fishing_speed:.2f}x", COLORS['text_light']),
            (f"幸运值: +{self.luck*100:.0f}%", COLORS['text_gold']),
            (f"自动捕鱼: {self.auto_fish:.1f}/s", (100, 200, 255)),
        ]
        for text, color in attrs:
            surface.blit(FONT_SMALL.render(text, True, color), (70, y))
            y += 28
        
        # 鱼类统计
        y += 10
        surface.blit(FONT_MEDIUM.render("鱼类统计:", True, COLORS['text_light']), (70, y))
        y += 35
        
        has_fish = False
        for name, count in sorted(self.fish_stats.items(), key=lambda x: x[1], reverse=True):
            if count > 0:
                has_fish = True
                color = FISH_TYPES[name]['color']
                surface.blit(FONT_SMALL.render(f"{name}: {count} 条", True, color), (80, y))
                y += 26
        
        if not has_fish:
            surface.blit(FONT_SMALL.render("还没有捕获任何鱼...", True, (150, 150, 150)), (80, y))
    
    def save_game(self):
        data = {
            'gold': self.gold, 'level': self.level, 'exp': self.exp,
            'exp_to_next': self.exp_to_next, 'total_caught': self.total_caught,
            'total_value': self.total_value, 'net_size': self.net_size,
            'fishing_speed': self.fishing_speed, 'luck': self.luck,
            'auto_fish': self.auto_fish, 'fish_stats': self.fish_stats,
        }
        try:
            with open('fish_save.json', 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
        except:
            pass
    
    def load_game(self):
        try:
            if os.path.exists('fish_save.json'):
                with open('fish_save.json', 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    for key, value in data.items():
                        if hasattr(self, key):
                            setattr(self, key, value)
        except:
            pass

def main():
    clock = pygame.time.Clock()
    game = FishingSimulator()
    running = True
    
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game.save_game()
                running = False
            
            if event.type == pygame.MOUSEMOTION:
                game.mouse_pos = event.pos
            
            if game.fish_button.handle_event(event):
                if game.current_page == 'main':
                    game.cast_net(game.mouse_pos[0], game.mouse_pos[1])
            
            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()