import pygame
import random

# --- 初始化 ---
pygame.init()
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("像素挖矿模拟器")
clock = pygame.time.Clock()

# 颜色定义
DIRT_COLOR = (101, 67, 33)
STONE_COLOR = (100, 100, 100)
GRASS_COLOR = (46, 204, 113)
PLAYER_COLOR = (52, 152, 219)

# 矿石颜色与价值
ORES = {
    'copper': {'color': (210, 105, 30), 'value': 10, 'prob': 0.15},
    'silver': {'color': (189, 195, 199), 'value': 25, 'prob': 0.08},
    'gold':   {'color': (241, 196, 15), 'value': 60, 'prob': 0.04},
    'diamond':{'color': (155, 89, 182), 'value': 150, 'prob': 0.01}
}

FONT = pygame.font.SysFont("arial", 24)
BIG_FONT = pygame.font.SysFont("arial", 36)

# --- 类定义 ---

class Particle:
    def __init__(self, x, y, color):
        self.x = x
        self.y = y
        self.color = color
        self.vx = random.uniform(-2, 2)
        self.vy = random.uniform(-2, 2)
        self.life = 30

    def update(self):
        self.x += self.vx
        self.y += self.vy
        self.life -= 1

    def draw(self, surface):
        pygame.draw.rect(surface, self.color, (int(self.x), int(self.y), 4, 4))

class Game:
    def __init__(self):
        self.tile_size = 40
        self.cols = WIDTH // self.tile_size
        self.rows = HEIGHT // self.tile_size
        
        # 玩家属性
        self.player_x = 10
        self.player_y = 5 # 从地表下方开始
        self.money = 0
        self.pickaxe_level = 1 # 1=普通, 2=铁, 3=金, 4=钻石
        
        # 地图生成
        self.map = []
        self.particles = []
        self.generate_map()
        
        # 浮动文字
        self.floating_texts = []

    def generate_map(self):
        self.map = []
        for r in range(self.rows):
            row = []
            for c in range(self.cols):
                if r == 0:
                    row.append('grass') # 地表
                else:
                    # 随机生成矿石
                    tile = 'dirt'
                    rand_val = random.random()
                    cumulative_prob = 0
                    
                    # 根据深度增加稀有矿石概率
                    depth_factor = min(1.0, r / 10) 
                    
                    if rand_val < ORES['diamond']['prob'] * depth_factor:
                        tile = 'diamond'
                    elif rand_val < (ORES['diamond']['prob'] + ORES['gold']['prob']) * depth_factor:
                        tile = 'gold'
                    elif rand_val < (ORES['diamond']['prob'] + ORES['gold']['prob'] + ORES['silver']['prob']) * depth_factor:
                        tile = 'silver'
                    elif rand_val < (ORES['diamond']['prob'] + ORES['gold']['prob'] + ORES['silver']['prob'] + ORES['copper']['prob']):
                        tile = 'copper'
                        
                    row.append(tile)
            self.map.append(row)

    def move_player(self, dx, dy):
        new_x = self.player_x + dx
        new_y = self.player_y + dy
        
        # 边界检查
        if 0 <= new_x < self.cols and 0 <= new_y < self.rows:
            target_tile = self.map[new_y][new_x]
            
            # 如果是石头或矿石，尝试挖掘
            if target_tile != 'grass' and target_tile != 'dirt':
                self.mine(new_x, new_y, target_tile)
            else:
                # 移动
                self.player_x = new_x
                self.player_y = new_y
                
                # 如果回到地表，自动卖钱 (这里简化为只要站在草地上就显示状态)
                if new_y == 0:
                    pass 

    def mine(self, x, y, ore_type):
        # 检查镐子等级是否足够挖掘 (简单设定：所有都能挖，但高等级有加成)
        # 实际逻辑：挖掘成功
        value = ORES[ore_type]['value']
        
        # 镐子等级加成
        multiplier = 1 + (self.pickaxe_level - 1) * 0.5
        final_value = int(value * multiplier)
        
        self.money += final_value
        self.map[y][x] = 'dirt' # 变成泥土
        
        # 特效
        for _ in range(10):
            px = x * self.tile_size + self.tile_size // 2
            py = y * self.tile_size + self.tile_size // 2
            self.particles.append(Particle(px, py, ORES[ore_type]['color']))
            
        self.floating_texts.append({
            'text': f"+${final_value}", 
            'x': x * self.tile_size, 
            'y': y * self.tile_size, 
            'life': 40
        })

    def upgrade_pickaxe(self):
        costs = [0, 100, 500, 2000] # 升级到下一级需要的钱
        if self.pickaxe_level < 4:
            cost = costs[self.pickaxe_level]
            if self.money >= cost:
                self.money -= cost
                self.pickaxe_level += 1
                self.floating_texts.append({
                    'text': "镐子升级!", 
                    'x': WIDTH//2 - 50, 
                    'y': HEIGHT//2, 
                    'life': 60
                })

    def update(self):
        # 更新粒子
        for p in self.particles[:]:
            p.update()
            if p.life <= 0: self.particles.remove(p)
            
        # 更新浮动文字
        for t in self.floating_texts[:]:
            t['y'] -= 1
            t['life'] -= 1
            if t['life'] <= 0: self.floating_texts.remove(t)

    def draw(self, surface):
        # 画地图
        for r in range(self.rows):
            for c in range(self.cols):
                rect = pygame.Rect(c * self.tile_size, r * self.tile_size, self.tile_size, self.tile_size)
                tile = self.map[r][c]
                
                color = DIRT_COLOR
                if tile == 'grass': color = GRASS_COLOR
                elif tile in ORES: color = ORES[tile]['color']
                
                pygame.draw.rect(surface, color, rect)
                pygame.draw.rect(surface, (0,0,0,50), rect, 1) # 网格线
                
                # 画矿石的小图标
                if tile in ORES:
                    center = (c * self.tile_size + 20, r * self.tile_size + 20)
                    pygame.draw.circle(surface, (255,255,255), center, 5)

        # 画玩家
        px = self.player_x * self.tile_size
        py = self.player_y * self.tile_size
        pygame.draw.rect(surface, PLAYER_COLOR, (px + 5, py + 5, 30, 30))
        
        # 画粒子
        for p in self.particles:
            p.draw(surface)
            
        # 画UI
        pygame.draw.rect(surface, (0,0,0), (0, HEIGHT-60, WIDTH, 60))
        info_text = FONT.render(f"金钱: ${self.money} | 镐子等级: {self.pickaxe_level}", True, (255,255,255))
        surface.blit(info_text, (20, HEIGHT - 40))
        
        # 升级提示
        if self.pickaxe_level < 4:
            next_cost = [100, 500, 2000][self.pickaxe_level - 1]
            upgrade_text = FONT.render(f"按 [SPACE] 升级镐子 (需要 ${next_cost})", True, (241, 196, 15))
            surface.blit(upgrade_text, (WIDTH - 350, HEIGHT - 40))
        else:
            max_text = FONT.render("镐子已达最高等级!", True, (241, 196, 15))
            surface.blit(max_text, (WIDTH - 250, HEIGHT - 40))

        # 画浮动文字
        for t in self.floating_texts:
            txt_surf = FONT.render(t['text'], True, (255, 255, 255))
            surface.blit(txt_surf, (t['x'], t['y']))

# --- 主程序 ---
game = Game()
running = True

while running:
    clock.tick(60)
    screen.fill((30, 30, 30))

    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP: game.move_player(0, -1)
            elif event.key == pygame.K_DOWN: game.move_player(0, 1)
            elif event.key == pygame.K_LEFT: game.move_player(-1, 0)
            elif event.key == pygame.K_RIGHT: game.move_player(1, 0)
            elif event.key == pygame.K_SPACE: game.upgrade_pickaxe()

    game.update()
    game.draw(screen)
    pygame.display.flip()

pygame.quit()