import pygame
import sys
import random
import math
import json
import os
from datetime import datetime

# 初始化Pygame
pygame.init()

# 屏幕设置
WINDOW_WIDTH = 1000
WINDOW_HEIGHT = 700
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("⛏️ 挖矿模拟器")

# 颜色
COLORS = {
    'background': (30, 30, 40),
    'panel_bg': (45, 45, 60),
    'panel_border': (80, 80, 100),
    'text_light': (240, 240, 240),
    'text_dark': (50, 50, 50),
    '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),
    'ore_common': (160, 160, 170),
    'ore_uncommon': (100, 200, 100),
    'ore_rare': (70, 130, 255),
    'ore_epic': (180, 80, 255),
    'ore_legendary': (255, 180, 50),
    'ore_mithril': (0, 200, 255),
    'progress_bg': (60, 60, 80),
    'progress_fill': (255, 215, 0),
    'shadow': (0, 0, 0, 100),
}

# ========== 中文字体支持 ==========
def get_chinese_font(size):
    """获取支持中文的字体"""
    font_paths = [
        "C:/Windows/Fonts/simsun.ttc",
        "C:/Windows/Fonts/simhei.ttf",
        "C:/Windows/Fonts/msyh.ttc",
        "C:/Windows/Fonts/STKAITI.TTF",
        "/System/Library/Fonts/PingFang.ttc",
        "/System/Library/Fonts/STHeiti Light.ttc",
        "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
        "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",
    ]
    for path in font_paths:
        try:
            if pygame.font.get_init():
                return pygame.font.Font(path, size)
        except:
            continue
    return pygame.font.Font(None, size)

FONT_TITLE = get_chinese_font(36)
FONT_LARGE = get_chinese_font(28)
FONT_MEDIUM = get_chinese_font(22)
FONT_SMALL = get_chinese_font(18)
FONT_TINY = get_chinese_font(14)

# ========== 矿石数据 ==========
ORE_TYPES = {
    '煤炭': {'color': COLORS['ore_common'], 'value': 5, 'exp': 10, 'chance': 0.35, 'emoji': '🪨'},
    '铜矿': {'color': COLORS['ore_uncommon'], 'value': 15, 'exp': 20, 'chance': 0.25, 'emoji': '🟫'},
    '铁矿': {'color': (180, 150, 120), 'value': 30, 'exp': 35, 'chance': 0.18, 'emoji': '⚒️'},
    '银矿': {'color': (200, 200, 210), 'value': 60, 'exp': 50, 'chance': 0.10, 'emoji': '💎'},
    '金矿': {'color': COLORS['ore_legendary'], 'value': 120, 'exp': 80, 'chance': 0.06, 'emoji': '🌟'},
    '钻石': {'color': COLORS['ore_epic'], 'value': 300, 'exp': 150, 'chance': 0.03, 'emoji': '💠'},
    '秘银': {'color': COLORS['ore_mithril'], 'value': 800, 'exp': 300, 'chance': 0.02, 'emoji': '🔮'},
    '远古遗物': {'color': (255, 80, 80), 'value': 2000, 'exp': 500, 'chance': 0.01, 'emoji': '🏆'},
}

# ========== 商店升级数据 ==========
UPGRADES = {
    'pickaxe': {
        'display_name': '镐子等级',
        'base_cost': 100,
        'cost_multiplier': 1.5,
        'description': '每次挖掘获得矿石 +20%',
        'max_level': 20,
        'effect_per_level': 0.2,
        'attr_name': 'pickaxe_level'
    },
    'speed': {
        'display_name': '挖掘速度',
        'base_cost': 80,
        'cost_multiplier': 1.4,
        'description': '挖掘冷却时间 -5%',
        'max_level': 15,
        'effect_per_level': 0.05,
        'attr_name': 'mining_speed'
    },
    'luck': {
        'display_name': '幸运值',
        'base_cost': 150,
        'cost_multiplier': 1.6,
        'description': '稀有矿石概率 +3%',
        'max_level': 10,
        'effect_per_level': 0.03,
        'attr_name': 'luck'
    },
    'auto': {
        'display_name': '自动挖掘',
        'base_cost': 500,
        'cost_multiplier': 2.0,
        'description': '每秒自动挖掘 0.5 次',
        'max_level': 10,
        'effect_per_level': 0.5,
        'attr_name': 'auto_mining'
    },
}

class Particle:
    """粒子效果"""
    def __init__(self, x, y, color, velocity, lifetime=30):
        self.x = x
        self.y = y
        self.color = color
        self.vx, self.vy = velocity
        self.lifetime = lifetime
        self.max_lifetime = lifetime
        self.size = random.randint(3, 8)
    
    def update(self):
        self.x += self.vx
        self.y += self.vy
        self.vy += 0.1
        self.lifetime -= 1
        return self.lifetime > 0
    
    def draw(self, surface):
        alpha = int(255 * (self.lifetime / self.max_lifetime))
        size = int(self.size * (self.lifetime / self.max_lifetime))
        if size > 0:
            pygame.draw.circle(surface, self.color, (int(self.x), int(self.y)), size)

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.hover = False
        self.pressed = False
        self.text_color = text_color if text_color else COLORS['text_light']
        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, 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 MiningSimulator:
    """挖矿模拟器主类"""
    def __init__(self):
        # 玩家数据
        self.gold = 0
        self.level = 1
        self.exp = 0
        self.exp_to_next = 100
        self.total_mined = 0
        
        # 技能数据
        self.pickaxe_level = 1
        self.mining_speed = 1.0
        self.luck = 0.0
        self.auto_mining = 0.0
        
        # 状态
        self.is_mining = False
        self.mining_progress = 0
        self.current_ore = None
        
        # 统计
        self.ore_stats = {ore: 0 for ore in ORE_TYPES}
        self.total_value = 0
        self.play_time = 0
        
        # 粒子系统
        self.particles = []
        
        # 消息系统
        self.messages = []
        
        # 当前页面: 'main', 'shop', 'stats'
        self.current_page = 'main'
        
        # ========== 创建按钮 ==========
        # 主页面按钮
        self.mine_button = Button(400, 450, 200, 60, "⛏️ 挖掘!", COLORS['button_green'])
        
        # 导航按钮（始终显示）
        self.shop_tab = Button(50, 580, 120, 40, "🏪 商店", COLORS['button_bg'])
        self.stats_tab = Button(180, 580, 120, 40, "📊 统计", COLORS['button_bg'])
        self.back_button = Button(320, 580, 120, 40, "🔙 返回", COLORS['button_red'])
        self.back_button.visible = False  # 默认隐藏
        
        # 商店按钮
        self.shop_buttons = {}
        self.init_shop_buttons()
        
        # 加载存档
        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']),
                'y_pos': y_pos,
                'data': data,
                'key': key
            }
            y_pos += 75
    
    def get_cooldown(self):
        """获取挖掘冷却时间（帧数）"""
        base = 60
        reduction = (self.mining_speed - 1.0) * 0.8
        return max(10, int(base * (1 - reduction)))
    
    def get_luck_bonus(self):
        """获取幸运加成"""
        return self.luck
    
    def get_mining_multiplier(self):
        """获取挖掘价值倍率"""
        return 1 + (self.pickaxe_level - 1) * 0.2
    
    def mine(self):
        """执行挖掘"""
        if self.is_mining:
            return
        
        self.is_mining = True
        self.mining_progress = 0
        
        rand = random.random()
        cumulative = 0
        selected_ore = '煤炭'
        
        luck_bonus = self.get_luck_bonus()
        
        for ore, data in ORE_TYPES.items():
            chance = data['chance']
            if ore not in ['煤炭', '铜矿']:
                chance = min(chance * (1 + luck_bonus), 0.5)
            cumulative += chance
            if rand < cumulative:
                selected_ore = ore
                break
        
        self.current_ore = selected_ore
    
    def complete_mining(self):
        """完成挖掘"""
        ore = self.current_ore
        if not ore:
            return
        
        data = ORE_TYPES[ore]
        
        multiplier = self.get_mining_multiplier()
        base_value = data['value']
        value = int(base_value * multiplier)
        exp_gain = data['exp']
        
        if random.random() < self.luck * 0.15:
            value = int(value * 1.5)
            self.add_message(f"✨ 幸运暴击! 获得 {value} 金币!", COLORS['text_gold'])
        
        self.gold += value
        self.exp += exp_gain
        self.total_mined += 1
        self.total_value += value
        self.ore_stats[ore] = self.ore_stats.get(ore, 0) + 1
        
        if self.exp >= self.exp_to_next:
            self.level_up()
        
        ore_color = data['color']
        for _ in range(20):
            angle = random.uniform(0, 2 * math.pi)
            speed = random.uniform(2, 8)
            self.particles.append(Particle(
                400 + random.randint(-30, 30),
                450 + random.randint(-30, 30),
                ore_color,
                (math.cos(angle) * speed, math.sin(angle) * speed - 2),
                random.randint(20, 50)
            ))
        
        self.add_message(f"⛏️ 获得 {ore} x1 (+{value}💰 +{exp_gain}经验)", COLORS['text_light'])
        
        self.current_ore = None
        self.is_mining = 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"🎉 升级! 等级 {self.level}! 奖励 {reward} 金币!", COLORS['text_gold'])
        
        for _ in range(40):
            angle = random.uniform(0, 2 * math.pi)
            speed = random.uniform(3, 10)
            self.particles.append(Particle(
                400, 300,
                COLORS['text_gold'],
                (math.cos(angle) * speed, math.sin(angle) * speed - 3),
                random.randint(30, 60)
            ))
    
    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, upgrade_key):
        """购买升级"""
        if upgrade_key not in UPGRADES:
            return
        
        data = UPGRADES[upgrade_key]
        attr_name = data['attr_name']
        current_level = getattr(self, attr_name)
        
        if current_level >= data['max_level']:
            self.add_message(f"⚠️ {data['display_name']} 已达到最高级!", COLORS['button_red'])
            return
        
        cost = int(data['base_cost'] * (data['cost_multiplier'] ** (current_level - 1)))
        
        if self.gold < cost:
            self.add_message(f"❌ 金币不足! 需要 {cost}💰", COLORS['button_red'])
            return
        
        self.gold -= cost
        setattr(self, attr_name, current_level + 1)
        
        self.add_message(f"✅ {data['display_name']} 升级到 {current_level + 1} 级!", COLORS['button_green'])
        self.save_game()
    
    def go_to_page(self, page):
        """切换页面"""
        self.current_page = page
        # 控制返回按钮显示
        if page == 'main':
            self.back_button.visible = False
        else:
            self.back_button.visible = True
    
    def update(self):
        """更新游戏状态"""
        if self.is_mining:
            self.mining_progress += 1
            cooldown = self.get_cooldown()
            if self.mining_progress >= cooldown:
                self.complete_mining()
        
        if self.auto_mining > 0:
            self.play_time += 1/60
            if random.random() < self.auto_mining / 60:
                self.mine()
                if self.is_mining:
                    self.mining_progress = self.get_cooldown() - 1
        
        self.particles = [p for p in self.particles if p.update()]
        
        for msg in self.messages:
            msg['time'] -= 1
        self.messages = [m for m in self.messages if m['time'] > 0]
    
    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)
        
        # 粒子
        for particle in self.particles:
            particle.draw(surface)
        
        self.draw_messages(surface)
    
    def draw_header(self, surface):
        """绘制顶部信息栏"""
        header_rect = pygame.Rect(0, 0, WINDOW_WIDTH, 70)
        pygame.draw.rect(surface, COLORS['panel_bg'], header_rect)
        pygame.draw.line(surface, COLORS['panel_border'], (0, 70), (WINDOW_WIDTH, 70), 2)
        
        gold_text = FONT_LARGE.render(f"💰 {self.gold:,}", True, COLORS['text_gold'])
        surface.blit(gold_text, (20, 18))
        
        exp_text = FONT_MEDIUM.render(f"🏆 Lv.{self.level}", True, COLORS['text_light'])
        surface.blit(exp_text, (250, 18))
        
        bar_rect = pygame.Rect(250, 45, 200, 18)
        pygame.draw.rect(surface, COLORS['progress_bg'], bar_rect, border_radius=9)
        if self.exp_to_next > 0:
            progress = min(self.exp / self.exp_to_next, 1)
            fill_rect = pygame.Rect(250, 45, int(200 * progress), 18)
            pygame.draw.rect(surface, COLORS['progress_fill'], fill_rect, border_radius=9)
        exp_text_small = FONT_TINY.render(f"{self.exp}/{self.exp_to_next}", True, COLORS['text_light'])
        surface.blit(exp_text_small, (255, 48))
        
        mined_text = FONT_MEDIUM.render(f"⛏️ {self.total_mined}", True, COLORS['text_light'])
        surface.blit(mined_text, (500, 20))
        
        if self.auto_mining > 0:
            auto_text = FONT_SMALL.render(f"🤖 自动: {self.auto_mining:.1f}/s", True, (100, 200, 255))
            surface.blit(auto_text, (620, 25))
    
    def draw_navigation(self, surface):
        """绘制导航栏"""
        # 导航栏背景
        nav_rect = pygame.Rect(0, 570, WINDOW_WIDTH, 60)
        pygame.draw.rect(surface, COLORS['panel_bg'], nav_rect)
        pygame.draw.line(surface, COLORS['panel_border'], (0, 570), (WINDOW_WIDTH, 570), 2)
        
        # 显示当前页面指示
        page_names = {
            'main': '⛏️ 挖矿',
            'shop': '🏪 商店',
            'stats': '📊 统计'
        }
        page_text = FONT_MEDIUM.render(f"当前: {page_names.get(self.current_page, '')}", True, COLORS['text_gold'])
        surface.blit(page_text, (700, 588))
        
        # 绘制按钮
        self.shop_tab.draw(surface)
        self.stats_tab.draw(surface)
        self.back_button.draw(surface)
    
    def draw_main(self, surface):
        """绘制主界面"""
        mine_rect = pygame.Rect(50, 90, 900, 350)
        pygame.draw.rect(surface, (25, 25, 35), mine_rect, border_radius=15)
        pygame.draw.rect(surface, COLORS['panel_border'], mine_rect, 2, border_radius=15)
        
        # 矿洞装饰
        for _ in range(30):
            x = random.randint(70, 930)
            y = random.randint(110, 410)
            size = random.randint(2, 6)
            brightness = random.randint(40, 80)
            pygame.draw.circle(surface, (brightness, brightness, brightness + 10), (x, y), size)
        
        if self.is_mining and self.current_ore:
            ore_data = ORE_TYPES[self.current_ore]
            ore_text = FONT_LARGE.render(f"正在挖掘: {self.current_ore}", True, ore_data['color'])
            surface.blit(ore_text, (370, 150))
        
        self.mine_button.draw(surface)
        
        if self.is_mining:
            progress = self.mining_progress / self.get_cooldown()
            bar_rect = pygame.Rect(400, 530, 200, 20)
            pygame.draw.rect(surface, COLORS['progress_bg'], bar_rect, border_radius=10)
            fill_rect = pygame.Rect(400, 530, int(200 * progress), 20)
            pygame.draw.rect(surface, COLORS['progress_fill'], fill_rect, border_radius=10)
    
    def draw_shop(self, surface):
        """绘制商店界面"""
        shop_rect = pygame.Rect(50, 90, 900, 450)
        pygame.draw.rect(surface, COLORS['panel_bg'], shop_rect, border_radius=15)
        pygame.draw.rect(surface, COLORS['panel_border'], shop_rect, 2, border_radius=15)
        
        title = FONT_LARGE.render("🏪 商店 - 升级你的装备!", True, COLORS['text_gold'])
        surface.blit(title, (70, 110))
        
        gold_text = FONT_MEDIUM.render(f"当前金币: {self.gold:,} 💰", True, COLORS['text_light'])
        surface.blit(gold_text, (70, 150))
        
        y_pos = 200
        for key, data in self.shop_buttons.items():
            upgrade_data = data['data']
            attr_name = upgrade_data['attr_name']
            current_level = getattr(self, attr_name)
            max_level = upgrade_data['max_level']
            
            level_text = FONT_MEDIUM.render(f"{upgrade_data['display_name']}: Lv.{current_level}/{max_level}", 
                                            True, COLORS['text_light'])
            surface.blit(level_text, (80, y_pos))
            
            desc_text = FONT_SMALL.render(upgrade_data['description'], True, (180, 180, 200))
            surface.blit(desc_text, (80, y_pos + 28))
            
            if current_level < max_level:
                cost = int(upgrade_data['base_cost'] * (upgrade_data['cost_multiplier'] ** (current_level - 1)))
                cost_text = FONT_SMALL.render(f"价格: {cost}💰", True, COLORS['text_gold'])
                surface.blit(cost_text, (80, y_pos + 50))
            else:
                cost_text = FONT_SMALL.render("已满级! 🎉", True, (100, 255, 100))
                surface.blit(cost_text, (80, y_pos + 50))
            
            data['button'].rect.y = y_pos
            data['button'].draw(surface)
            
            y_pos += 75
    
    def draw_stats(self, surface):
        """绘制统计界面"""
        stats_rect = pygame.Rect(50, 90, 900, 450)
        pygame.draw.rect(surface, COLORS['panel_bg'], stats_rect, border_radius=15)
        pygame.draw.rect(surface, COLORS['panel_border'], stats_rect, 2, border_radius=15)
        
        title = FONT_LARGE.render("📊 统计信息", True, COLORS['text_gold'])
        surface.blit(title, (70, 110))
        
        total_text = FONT_MEDIUM.render(f"总挖掘次数: {self.total_mined}", True, COLORS['text_light'])
        surface.blit(total_text, (70, 160))
        
        total_value_text = FONT_MEDIUM.render(f"总收益: {self.total_value:,} 💰", True, COLORS['text_gold'])
        surface.blit(total_value_text, (70, 195))
        
        y_pos = 240
        attr_title = FONT_MEDIUM.render("当前属性:", True, COLORS['text_light'])
        surface.blit(attr_title, (70, y_pos))
        y_pos += 35
        
        attrs = [
            (f"镐子等级: Lv.{self.pickaxe_level}", COLORS['text_light']),
            (f"挖掘速度: {self.mining_speed:.2f}x", COLORS['text_light']),
            (f"幸运值: +{self.luck*100:.0f}%", COLORS['text_gold']),
            (f"自动挖掘: {self.auto_mining:.1f}/s", (100, 200, 255)),
        ]
        for text, color in attrs:
            attr_text = FONT_SMALL.render(text, True, color)
            surface.blit(attr_text, (80, y_pos))
            y_pos += 28
        
        y_pos += 10
        ore_title = FONT_MEDIUM.render("矿石分布:", True, COLORS['text_light'])
        surface.blit(ore_title, (70, y_pos))
        y_pos += 35
        
        has_ore = False
        for ore, count in sorted(self.ore_stats.items(), key=lambda x: x[1], reverse=True):
            if count > 0:
                has_ore = True
                data = ORE_TYPES[ore]
                text = FONT_SMALL.render(f"{data['emoji']} {ore}: {count} 个", True, data['color'])
                surface.blit(text, (80, y_pos))
                y_pos += 28
        
        if not has_ore:
            empty_text = FONT_SMALL.render("还没有挖掘任何矿石...", True, (150, 150, 150))
            surface.blit(empty_text, (80, y_pos))
    
    def draw_messages(self, surface):
        """绘制消息"""
        y_pos = 620
        for msg in reversed(self.messages[-5:]):
            alpha = min(255, msg['time'] * 2)
            text_surf = FONT_SMALL.render(msg['text'], True, msg['color'])
            text_surf.set_alpha(alpha)
            surface.blit(text_surf, (20, y_pos))
            y_pos -= 22
    
    def save_game(self):
        """保存游戏"""
        save_data = {
            'gold': self.gold,
            'level': self.level,
            'exp': self.exp,
            'exp_to_next': self.exp_to_next,
            'total_mined': self.total_mined,
            'total_value': self.total_value,
            'pickaxe_level': self.pickaxe_level,
            'mining_speed': self.mining_speed,
            'luck': self.luck,
            'auto_mining': self.auto_mining,
            'ore_stats': self.ore_stats,
            'play_time': self.play_time,
        }
        try:
            with open('mining_save.json', 'w', encoding='utf-8') as f:
                json.dump(save_data, f, ensure_ascii=False, indent=2)
        except:
            pass
    
    def load_game(self):
        """加载游戏"""
        try:
            if os.path.exists('mining_save.json'):
                with open('mining_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)
                self.add_message("💾 游戏已加载!", COLORS['text_gold'])
        except:
            pass

def main():
    clock = pygame.time.Clock()
    game = MiningSimulator()
    running = True
    
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game.save_game()
                running = False
            
            # 挖掘按钮（仅主页面可用）
            if game.mine_button.handle_event(event):
                if game.current_page == 'main' and not game.is_mining:
                    game.mine()
            
            # 导航按钮
            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()