import pygame
import random
import math
import json
import os

pygame.init()

# 窗口设置
WIDTH = 1100
HEIGHT = 900
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("✈️ 飞行躲避大冒险")
clock = pygame.time.Clock()
FPS = 60

# 颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (227, 37, 37)
GREEN = (0, 217, 77)
BLUE = (37, 174, 237)
YELLOW = (255, 223, 84)
PURPLE = (229, 93, 195)
ORANGE = (255, 160, 30)
CYAN = (37, 197, 217)
DARK = (18, 22, 30)
GRAY = (140, 143, 148)
GOLD = (255, 193, 17)

# 字体
font_tiny = pygame.font.Font(None, 22)
font_small = pygame.font.Font(None, 28)
font_mid = pygame.font.Font(None, 36)
font_big = pygame.font.Font(None, 54)
font_huge = pygame.font.Font(None, 72)

# 皮肤数据
SKINS = {
    "default": {
        "name": "🛩️ 默认飞机",
        "color": (37, 197, 217),
        "price": 0,
        "shape": "jet",
        "desc": "新手标配，轻巧灵活",
        "ability": "基础速度 +0%"
    },
    "golden": {
        "name": "🌟 黄金战机",
        "color": (255, 193, 17),
        "price": 100,
        "shape": "jet",
        "desc": "镀金机身，闪耀全场",
        "ability": "金币获取 +20%"
    },
    "red_fire": {
        "name": "🐉 烈焰飞龙",
        "color": (227, 37, 37),
        "price": 200,
        "shape": "dragon",
        "desc": "传说级龙族战机，烈焰吐息",
        "ability": "碰撞体积 -15%"
    },
    "dark_knight": {
        "name": "⚔️ 暗夜骑士",
        "color": (229, 93, 195),
        "price": 300,
        "shape": "knight",
        "desc": "暗影战士，最强防御力场",
        "ability": "初始护盾 +1次"
    },
    "rainbow": {
        "name": "🌈 彩虹幻影",
        "color": (255, 97, 201),
        "price": 500,
        "shape": "magic",
        "desc": "终极战机，操控时空",
        "ability": "无敌时间 +50%"
    },
}

# 地图配置
MAPS = {
    "classic": {
        "name": "☁️ 经典天空",
        "bg_color": (46, 75, 119),
        "clouds": True,
        "desc": "蓝天白云，轻松上手",
        "difficulty": "★☆☆☆☆"
    },
    "space": {
        "name": "🌌 星际穿越",
        "bg_color": (5, 5, 29),
        "stars": True,
        "desc": "浩瀚宇宙，星光璀璨",
        "difficulty": "★★☆☆☆"
    },
    "fire": {
        "name": "🌋 火焰地狱",
        "bg_color": (41, 10, 9),
        "lava": True,
        "desc": "熔岩地狱，炙热难耐",
        "difficulty": "★★★☆☆"
    },
    "forest": {
        "name": "🌲 森林迷雾",
        "bg_color": (15, 41, 19),
        "leaves": True,
        "desc": "密林深处，视线受阻",
        "difficulty": "★★★★☆"
    },
    "neon": {
        "name": "💜 霓虹都市",
        "bg_color": (10, 10, 29),
        "neon": True,
        "desc": "赛博之城，极速狂飙",
        "difficulty": "★★★★★"
    },
}

class Player:
    def __init__(self, skin_id="default"):
        self.x = 120
        self.y = HEIGHT // 2
        self.width = 42
        self.height = 32
        self.speed = 5
        self.skin = SKINS[skin_id]
        self.skin_id = skin_id
        self.invincible = 0
        self.alive = True
        self.shield = 1 if skin_id == "dark_knight" else 0
        
    def move(self, keys):
        if not self.alive:
            return
        if keys[pygame.K_UP] or keys[pygame.K_w]:
            self.y -= self.speed
        if keys[pygame.K_DOWN] or keys[pygame.K_s]:
            self.y += self.speed
        if keys[pygame.K_LEFT] or keys[pygame.K_a]:
            self.x -= self.speed
        if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
            self.x += self.speed
            
        self.x = max(20, min(WIDTH-60, self.x))
        self.y = max(20, min(HEIGHT-50, self.y))
        
        if self.invincible > 0:
            self.invincible -= 1
    
    def draw(self, surface):
        if not self.alive:
            return
        if self.invincible > 0 and self.invincible % 5 < 2:
            return
            
        color = self.skin["color"]
        shape = self.skin["shape"]
        x, y = self.x, self.y
        
        if shape == "jet":
            points = [(x+42, y+16), (x, y), (x+12, y+16), (x, y+32)]
            pygame.draw.polygon(surface, color, points)
            pygame.draw.polygon(surface, WHITE, [(x+22, y+10), (x+32, y+16), (x+22, y+22)], 2)
            pygame.draw.polygon(surface, ORANGE, [(x, y+6), (x-15, y+16), (x, y+26)])
            
        elif shape == "dragon":
            pygame.draw.ellipse(surface, color, (x, y, 42, 32))
            pygame.draw.polygon(surface, color, [(x+42, y+16), (x+58, y+5), (x+58, y+27)])
            pygame.draw.polygon(surface, RED, [(x+42, y+16), (x+52, y+10), (x+52, y+22)])
            wing1 = [(x+16, y), (x+5, y-15), (x+26, y-5)]
            pygame.draw.polygon(surface, color, wing1)
            wing2 = [(x+16, y+32), (x+5, y+47), (x+26, y+37)]
            pygame.draw.polygon(surface, color, wing2)
            
        elif shape == "knight":
            pygame.draw.rect(surface, color, (x, y+5, 37, 22), border_radius=5)
            pygame.draw.polygon(surface, color, [(x+37, y+16), (x+53, y+8), (x+53, y+24)])
            pygame.draw.rect(surface, DARK, (x+5, y, 27, 8), border_radius=3)
            pygame.draw.line(surface, WHITE, (x+48, y+16), (x+63, y+5), 3)
            
        elif shape == "magic":
            pygame.draw.ellipse(surface, color, (x, y, 37, 32))
            pygame.draw.circle(surface, color, (x+42, y+16), 12)
            for i in range(3):
                alpha = 90 - i*28
                r = 25 + i*8
                circle = pygame.Surface((r*2, r*2), pygame.SRCALPHA)
                pygame.draw.circle(circle, (*color[:3], alpha), (r, r), r, 2)
                surface.blit(circle, (x+21-r, y+16-r))

class Obstacle:
    def __init__(self, speed, map_type):
        self.x = WIDTH + 50
        self.y = random.randint(30, HEIGHT-30)
        self.width = random.randint(20, 45)
        self.height = random.randint(20, 45)
        self.speed = speed + random.uniform(-0.5, 1.0)
        self.type = random.choice(["rock", "bird", "missile", "laser"])
        self.map_type = map_type
        self.angle = 0
        self.invisible = False
        if map_type == "forest" and random.random() < 0.3:
            self.invisible = True
        
    def move(self):
        self.x -= self.speed
        self.angle += 2
        
    def draw(self, surface):
        if self.invisible and self.x > WIDTH - 150:
            return
            
        x, y = self.x, self.y
        w, h = self.width, self.height
        alpha = 80 if self.invisible else 255
        
        if self.type == "rock":
            color = (120, 110, 100)
            s = pygame.Surface((w, h), pygame.SRCALPHA)
            pygame.draw.ellipse(s, (*color, alpha), (0, 0, w, h))
            pygame.draw.ellipse(s, (90, 80, 70, alpha), (3, 3, w-6, h-6))
            surface.blit(s, (x, y))
            
        elif self.type == "bird":
            color = (80, 60, 50)
            s = pygame.Surface((w+20, h+20), pygame.SRCALPHA)
            pygame.draw.ellipse(s, (*color, alpha), (10, 10, w, h))
            wing_y = 10 + h//2
            pygame.draw.polygon(s, (*color, alpha), [(10, wing_y), (0, wing_y-15), (10+w, wing_y)])
            pygame.draw.polygon(s, (*color, alpha), [(10, wing_y), (0, wing_y+15), (10+w, wing_y)])
            pygame.draw.circle(s, (255, 0, 0, alpha), (int(10+w*0.7), int(10+h*0.3)), 3)
            surface.blit(s, (x-10, y-10))
            
        elif self.type == "missile":
            color = RED
            s = pygame.Surface((w+25, h+10), pygame.SRCALPHA)
            pygame.draw.rect(s, (*color, alpha), (25, 5, w, h-10), border_radius=3)
            pygame.draw.polygon(s, (*color, alpha), [(25, 5), (10, 5+h//2), (25, h-5)])
            flame_len = random.randint(10, 25)
            pygame.draw.polygon(s, (255, 160, 30, alpha), [(25+w, 5), (25+w+flame_len, 5+h//2), (25+w, h-5)])
            surface.blit(s, (x-25, y-5))
            
        elif self.type == "laser":
            color = (255, 50, 255) if self.map_type == "neon" else (255, 200, 50)
            s = pygame.Surface((w+10, h+10), pygame.SRCALPHA)
            pygame.draw.ellipse(s, (*color, alpha), (5, 5, w, h))
            glow = pygame.Surface((w+20, h+20), pygame.SRCALPHA)
            pygame.draw.ellipse(glow, (*color[:3], 80), (10, 10, w, h))
            surface.blit(glow, (x-10, y-10))
            surface.blit(s, (x-5, y-5))

class Coin:
    def __init__(self):
        self.x = WIDTH + 20
        self.y = random.randint(30, HEIGHT-30)
        self.size = 13
        self.collected = False
        
    def move(self, speed):
        self.x -= speed
        
    def draw(self, surface):
        if self.collected:
            return
        width = self.size if random.random() > 0.3 else self.size * 0.3
        pygame.draw.ellipse(surface, GOLD, (self.x-width//2, self.y-self.size//2, width, self.size))
        pygame.draw.ellipse(surface, (200, 150, 20), (self.x-width//2, self.y-self.size//2, width, self.size), 2)
        if width > self.size * 0.5:
            pygame.draw.circle(surface, (200, 150, 20), (self.x, self.y), 3)

class Particle:
    def __init__(self, x, y, color):
        self.x = x
        self.y = y
        self.vx = random.uniform(-3, 3)
        self.vy = random.uniform(-3, 3)
        self.life = random.randint(20, 40)
        self.max_life = self.life
        self.color = color
        self.size = random.randint(2, 5)
        
    def update(self):
        self.x += self.vx
        self.y += self.vy
        self.life -= 1
        return self.life > 0
        
    def draw(self, surface):
        alpha = int(255 * self.life / self.max_life)
        s = pygame.Surface((self.size*2, self.size*2), pygame.SRCALPHA)
        pygame.draw.circle(s, (*self.color, alpha), (self.size, self.size), self.size)
        surface.blit(s, (int(self.x-self.size), int(self.y-self.size)))

class Background:
    def __init__(self, map_type):
        self.map_type = map_type
        self.config = MAPS[map_type]
        self.elements = []
        self.scroll = 0
        
        if map_type == "classic":
            for _ in range(15):
                self.elements.append({
                    "x": random.randint(0, WIDTH),
                    "y": random.randint(0, HEIGHT),
                    "size": random.randint(20, 60),
                    "speed": random.uniform(0.2, 0.8)
                })
        elif map_type == "space":
            for _ in range(50):
                self.elements.append({
                    "x": random.randint(0, WIDTH),
                    "y": random.randint(0, HEIGHT),
                    "size": random.randint(1, 3),
                    "brightness": random.randint(100, 255)
                })
        elif map_type == "fire":
            for _ in range(10):
                self.elements.append({
                    "x": random.randint(0, WIDTH),
                    "y": random.randint(HEIGHT-100, HEIGHT),
                    "width": random.randint(30, 100),
                    "height": random.randint(10, 30),
                    "phase": random.uniform(0, 6.28)
                })
        elif map_type == "forest":
            for _ in range(20):
                self.elements.append({
                    "x": random.randint(0, WIDTH),
                    "y": random.randint(0, HEIGHT),
                    "size": random.randint(5, 15),
                    "shade": random.randint(30, 80)
                })
        elif map_type == "neon":
            for _ in range(8):
                self.elements.append({
                    "x": random.randint(0, WIDTH),
                    "y": random.randint(0, HEIGHT),
                    "length": random.randint(50, 200),
                    "color": random.choice([RED, BLUE, GREEN, GOLD, PURPLE]),
                    "speed": random.uniform(0.5, 2)
                })
    
    def update(self):
        self.scroll += 1
        
    def draw(self, surface):
        bg = self.config["bg_color"]
        surface.fill(bg)
        
        map_type = self.map_type
        
        if map_type == "classic":
            for el in self.elements:
                el["x"] -= el["speed"]
                if el["x"] < -el["size"]:
                    el["x"] = WIDTH + el["size"]
                alpha = 40
                cloud = pygame.Surface((el["size"], el["size"]//2), pygame.SRCALPHA)
                pygame.draw.ellipse(cloud, (255, 255, 255, alpha), (0, 0, el["size"], el["size"]//2))
                surface.blit(cloud, (el["x"], el["y"]))
                
        elif map_type == "space":
            for el in self.elements:
                b = el["brightness"]
                pygame.draw.circle(surface, (b, b, b), (int(el["x"]), int(el["y"])), el["size"])
                if random.random() < 0.005:
                    el["brightness"] = random.randint(150, 255)
                    
        elif map_type == "fire":
            for el in self.elements:
                height_var = int(math.sin(self.scroll * 0.05 + el["phase"]) * 10)
                lava_y = el["y"] + height_var
                pygame.draw.ellipse(surface, (200, 50, 10), 
                                   (el["x"], lava_y, el["width"], el["height"]))
                pygame.draw.ellipse(surface, (255, 100, 20),
                                   (el["x"]+5, lava_y-3, el["width"]-10, el["height"]-4))
                                   
        elif map_type == "forest":
            for el in self.elements:
                shade = el["shade"]
                pygame.draw.circle(surface, (0, shade, 0), (int(el["x"]), int(el["y"])), el["size"])
                if random.random() < 0.02:
                    el["y"] += 1
                    if el["y"] > HEIGHT:
                        el["y"] = 0
                        el["x"] = random.randint(0, WIDTH)
                        
        elif map_type == "neon":
            for el in self.elements:
                el["x"] -= el["speed"]
                if el["x"] < -el["length"]:
                    el["x"] = WIDTH + 50
                    el["y"] = random.randint(0, HEIGHT)
                color = el["color"]
                for i in range(3):
                    alpha = 30 - i*10
                    line = pygame.Surface((el["length"], 2), pygame.SRCALPHA)
                    line.fill((*color[:3], alpha))
                    surface.blit(line, (el["x"], el["y"] + i*4))

class Game:
    def __init__(self):
        self.load_data()
        self.reset()
        
    def reset(self):
        """新游戏重置 - 金币归零"""
        self.state = "menu"
        self.player = Player(self.current_skin if hasattr(self, 'current_skin') else "default")
        self.obstacles = []
        self.coins = []
        self.particles = []
        self.score = 0
        self.coins_collected = 0
        self.time = 0
        self.obstacle_timer = 0
        self.coin_timer = 0
        self.difficulty = 1
        self.speed = 4
        self.combo = 0
        self.max_combo = 0
        self.selected_map = "classic"
        self.background = Background(self.selected_map)
        self.shop_page = 0
        self.show_intro = True
        # 新游戏金币归零（但保留已购买的皮肤和地图）
        self.total_coins = 0
        self.save_data()
        
    def load_data(self):
        """读取存档"""
        self.data_file = "flight_data.json"
        if os.path.exists(self.data_file):
            with open(self.data_file, 'r') as f:
                data = json.load(f)
                self.total_coins = data.get("coins", 0)
                self.high_score = data.get("high_score", 0)
                self.owned_skins = data.get("skins", ["default"])
                self.current_skin = data.get("current_skin", "default")
                self.unlocked_maps = data.get("maps", ["classic"])
        else:
            self.total_coins = 0
            self.high_score = 0
            self.owned_skins = ["default"]
            self.current_skin = "default"
            self.unlocked_maps = ["classic"]
    
    def save_data(self):
        """保存存档"""
        data = {
            "coins": self.total_coins,
            "high_score": max(self.high_score, self.score),
            "skins": self.owned_skins,
            "current_skin": self.current_skin,
            "maps": self.unlocked_maps
        }
        with open(self.data_file, 'w') as f:
            json.dump(data, f)
    
    def add_particles(self, x, y, color, count=10):
        for _ in range(count):
            self.particles.append(Particle(x, y, color))
    
    def handle_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return False
                
            if event.type == pygame.KEYDOWN:
                if self.state == "menu":
                    if event.key == pygame.K_1:
                        self.reset()  # 新游戏，金币归零
                        self.state = "playing"
                    elif event.key == pygame.K_2:
                        self.state = "shop"
                    elif event.key == pygame.K_3:
                        self.state = "map_select"
                    elif event.key == pygame.K_i:
                        self.show_intro = not self.show_intro
                    elif event.key == pygame.K_l:
                        self.load_data()  # 手动读档
                        self.save_message = "📂 读取存档成功！"
                        self.save_message_timer = 120
                        
                elif self.state == "playing":
                    if event.key == pygame.K_ESCAPE or event.key == pygame.K_p:
                        self.state = "paused"
                    elif event.key == pygame.K_s:
                        self.save_data()  # 手动存档
                        self.save_message = "💾 存档成功！"
                        self.save_message_timer = 120
                        
                elif self.state == "paused":
                    if event.key == pygame.K_p or event.key == pygame.K_ESCAPE:
                        self.state = "playing"
                    elif event.key == pygame.K_q:
                        self.state = "menu"
                    elif event.key == pygame.K_s:
                        self.save_data()
                        self.save_message = "💾 存档成功！"
                        self.save_message_timer = 120
                        
                elif self.state == "game_over":
                    if event.key == pygame.K_SPACE:
                        self.state = "menu"
                        
                elif self.state == "shop":
                    if event.key == pygame.K_LEFT:
                        self.shop_page = 0
                    elif event.key == pygame.K_RIGHT:
                        self.shop_page = 1
                    elif event.key == pygame.K_ESCAPE or event.key == pygame.K_q:
                        self.state = "menu"
                        
                elif self.state == "map_select":
                    if event.key == pygame.K_ESCAPE or event.key == pygame.K_q:
                        self.state = "menu"
                        
        return True
    
    def update(self):
        if self.state != "playing":
            return
            
        keys = pygame.key.get_pressed()
        self.player.move(keys)
        
        self.time += 1
        self.difficulty = 1 + self.time // 720
        self.speed = 4 + self.difficulty * 0.5
        
        if self.selected_map == "neon":
            self.speed *= 1.5
        
        self.obstacle_timer += 1
        spawn_rate = max(15, 50 - self.difficulty * 3)
        if self.selected_map == "fire":
            spawn_rate = int(spawn_rate * 0.7)
        if self.obstacle_timer >= spawn_rate:
            self.obstacle_timer = 0
            self.obstacles.append(Obstacle(self.speed, self.selected_map))
            if self.difficulty > 3 and random.random() < 0.3:
                self.obstacles.append(Obstacle(self.speed, self.selected_map))
        
        self.coin_timer += 1
        if self.coin_timer >= random.randint(30, 80):
            self.coin_timer = 0
            self.coins.append(Coin())
        
        for obs in self.obstacles[:]:
            obs.move()
            if obs.x < -obs.width:
                self.obstacles.remove(obs)
        
        for coin in self.coins[:]:
            coin.move(self.speed)
            if coin.x < -20:
                self.coins.remove(coin)
        
        player_rect = pygame.Rect(self.player.x, self.player.y, self.player.width, self.player.height)
        
        collision_mult = 0.618
        if self.player.skin_id == "red_fire":
            collision_mult = 0.421
        
        for obs in self.obstacles[:]:
            obs_rect = pygame.Rect(obs.x, obs.y, obs.width, obs.height)
            pw = int(player_rect.width * collision_mult)
            ph = int(player_rect.height * collision_mult)
            small_rect = pygame.Rect(player_rect.centerx - pw//2, player_rect.centery - ph//2, pw, ph)
            
            if small_rect.colliderect(obs_rect):
                if self.player.invincible <= 0:
                    if self.player.shield > 0:
                        self.player.shield -= 1
                        self.player.invincible = 120
                        self.add_particles(self.player.x+20, self.player.y+15, WHITE, 15)
                    else:
                        self.player.alive = False
                        self.add_particles(self.player.x+20, self.player.y+15, ORANGE, 20)
                        self.state = "game_over"
                        self.save_data()
                        return
        
        for coin in self.coins[:]:
            if not coin.collected:
                coin_rect = pygame.Rect(coin.x-coin.size, coin.y-coin.size, coin.size*2, coin.size*2)
                if player_rect.colliderect(coin_rect):
                    coin.collected = True
                    self.coins_collected += 1
                    
                    coin_bonus = 1
                    if self.player.skin_id == "golden":
                        coin_bonus = 2
                    
                    self.total_coins += coin_bonus
                    self.combo += 1
                    self.max_combo = max(self.max_combo, self.combo)
                    bonus = 1 + self.combo // 5
                    self.score += 10 * bonus
                    self.add_particles(coin.x, coin.y, GOLD, 8)
                    self.coins.remove(coin)
        
        self.particles = [p for p in self.particles if p.update()]
        self.background.update()
    
    def draw_button(self, surface, text, x, y, w, h, color, text_color=WHITE, hover=False):
        if hover:
            pygame.draw.rect(surface, (min(color[0]+30, 255), min(color[1]+30, 255), min(color[2]+30, 255)), 
                           (x, y, w, h), border_radius=10)
        else:
            pygame.draw.rect(surface, color, (x, y, w, h), border_radius=10)
        pygame.draw.rect(surface, WHITE, (x, y, w, h), 2, border_radius=10)
        label = font_mid.render(text, True, text_color)
        surface.blit(label, (x + w//2 - label.get_width()//2, y + h//2 - label.get_height()//2))
    
    def draw_menu(self):
        screen.fill(DARK)
        
        for _ in range(3):
            x = random.randint(0, WIDTH)
            y = random.randint(0, HEIGHT)
            pygame.draw.circle(screen, (60, 80, 120), (x, y), random.randint(1, 3))
        
        title = font_huge.render("✈️ 飞行躲避", True, CYAN)
        screen.blit(title, (WIDTH//2 - title.get_width()//2, 30))
        
        sub = font_mid.render("大冒险", True, GOLD)
        screen.blit(sub, (WIDTH//2 - sub.get_width()//2, 95))
        
        stats = [
            f"🏆 最高分: {self.high_score}",
            f"💰 总金币: {self.total_coins}",
            f"🔥 最大连击: {self.max_combo}",
        ]
        y = 150
        for stat in stats:
            label = font_small.render(stat, True, GRAY)
            screen.blit(label, (WIDTH//2 - label.get_width()//2, y))
            y += 30
        
        current_skin_name = SKINS[self.current_skin]["name"]
        current_map_name = MAPS[self.selected_map]["name"]
        info = font_tiny.render(f"当前皮肤: {current_skin_name}  |  当前地图: {current_map_name}", True, GRAY)
        screen.blit(info, (WIDTH//2 - info.get_width()//2, y+5))
        
        buttons = [
            ("1️⃣  开始游戏", 250, BLUE),
            ("2️⃣  商店", 320, PURPLE),
            ("3️⃣  选择地图", 390, GREEN),
            ("I  游戏介绍", 460, (80, 80, 100)),
        ]
        
        for text, y, color in buttons:
            self.draw_button(screen, text, WIDTH//2-120, y, 240, 45, color)
        
        # 存档/读档提示
        save_hint = font_tiny.render("S: 游戏中存档  |  L: 主菜单读档", True, GRAY)
        screen.blit(save_hint, (WIDTH//2 - save_hint.get_width()//2, 520))
        
        if hasattr(self, 'save_message') and self.save_message:
            msg_label = font_small.render(self.save_message, True, GOLD)
            screen.blit(msg_label, (WIDTH//2 - msg_label.get_width()//2, 545))
            self.save_message_timer -= 1
            if self.save_message_timer <= 0:
                self.save_message = ""
        
        if self.show_intro:
            intro_surf = pygame.Surface((WIDTH-100, 100), pygame.SRCALPHA)
            intro_surf.fill((20, 25, 35, 220))
            screen.blit(intro_surf, (50, 560))
            
            intro_lines = [
                "🎮 游戏说明",
                "方向键/WASD 移动  |  收集金币得高分  |  躲避障碍物",
                "不同皮肤有特殊能力  |  5种地图难度各异",
                "S键游戏中存档  |  L键主菜单读档"
            ]
            iy = 568
            for line in intro_lines:
                if line.startswith("🎮"):
                    label = font_mid.render(line, True, GOLD)
                else:
                    label = font_tiny.render(line, True, GRAY)
                screen.blit(label, (60, iy))
                iy += 22
        
        tip = font_tiny.render("方向键/WASD移动  P暂停  I开关介绍  S存档  L读档", True, GRAY)
        screen.blit(tip, (WIDTH//2 - tip.get_width()//2, HEIGHT-30))
    
    def draw_shop(self):
        screen.fill(DARK)
        
        title = font_big.render("🏪 商店", True, GOLD)
        screen.blit(title, (WIDTH//2 - title.get_width()//2, 30))
        
        coins_text = font_mid.render(f"💰 {self.total_coins} 金币", True, GOLD)
        screen.blit(coins_text, (WIDTH//2 - coins_text.get_width()//2, 85))
        
        page_text = font_tiny.render("← 飞机皮肤  道具 →", True, GRAY)
        screen.blit(page_text, (WIDTH//2 - page_text.get_width()//2, 120))
        
        if self.shop_page == 0:
            y = 155
            for skin_id, skin in SKINS.items():
                owned = skin_id in self.owned_skins
                selected = skin_id == self.current_skin
                
                temp_player = Player(skin_id)
                temp_player.x = 40
                temp_player.y = y + 20
                temp_player.draw(screen)
                
                name_text = font_mid.render(skin["name"], True, WHITE)
                screen.blit(name_text, (90, y+5))
                
                desc_label = font_tiny.render(skin["desc"], True, GRAY)
                screen.blit(desc_label, (90, y+30))
                
                ability_label = font_tiny.render(f"✨ {skin['ability']}", True, CYAN)
                screen.blit(ability_label, (400, y+10))
                
                if selected:
                    status = "✅ 使用中"
                    status_color = GREEN
                elif owned:
                    status = "✓ 已拥有"
                    status_color = GRAY
                else:
                    status = f"💰 {skin['price']} 金币"
                    status_color = GOLD
                
                status_label = font_small.render(status, True, status_color)
                screen.blit(status_label, (400, y+35))
                
                btn_x, btn_y = 600, y+15
                btn_w, btn_h = 110, 35
                
                mouse = pygame.mouse.get_pos()
                click = pygame.mouse.get_pressed()[0]
                
                if selected:
                    self.draw_button(screen, "使用中", btn_x, btn_y, btn_w, btn_h, GREEN, WHITE)
                elif owned:
                    if btn_x < mouse[0] < btn_x+btn_w and btn_y < mouse[1] < btn_y+btn_h:
                        self.draw_button(screen, "装备", btn_x, btn_y, btn_w, btn_h, BLUE)
                        if click:
                            self.current_skin = skin_id
                            self.save_data()
                    else:
                        self.draw_button(screen, "装备", btn_x, btn_y, btn_w, btn_h, (60, 60, 80))
                else:
                    can_afford = self.total_coins >= skin["price"]
                    if can_afford:
                        if btn_x < mouse[0] < btn_x+btn_w and btn_y < mouse[1] < btn_y+btn_h:
                            self.draw_button(screen, "购买", btn_x, btn_y, btn_w, btn_h, GREEN)
                            if click:
                                self.total_coins -= skin["price"]
                                self.owned_skins.append(skin_id)
                                self.current_skin = skin_id
                                self.save_data()
                        else:
                            self.draw_button(screen, "购买", btn_x, btn_y, btn_w, btn_h, (60, 80, 60))
                    else:
                        self.draw_button(screen, "购买", btn_x, btn_y, btn_w, btn_h, (80, 40, 40))
                
                y += 80
        else:
            items_text = font_mid.render("🎁 更多道具即将上线...", True, GRAY)
            screen.blit(items_text, (WIDTH//2 - items_text.get_width()//2, HEIGHT//2-20))
            
            coming = font_small.render("敬请期待！", True, GRAY)
            screen.blit(coming, (WIDTH//2 - coming.get_width()//2, HEIGHT//2+20))
        
        self.draw_button(screen, "ESC 返回", WIDTH//2-80, HEIGHT-60, 160, 40, (60, 60, 80))
    
    def draw_map_select(self):
        screen.fill(DARK)
        
        title = font_big.render("🗺️ 选择地图", True, GREEN)
        screen.blit(title, (WIDTH//2 - title.get_width()//2, 30))
        
        y = 100
        for map_id, map_config in MAPS.items():
            unlocked = map_id in self.unlocked_maps
            selected = map_id == self.selected_map
            
            preview_rect = pygame.Rect(40, y, 90, 60)
            pygame.draw.rect(screen, map_config["bg_color"], preview_rect, border_radius=5)
            pygame.draw.rect(screen, WHITE, preview_rect, 2, border_radius=5)
            
            name_text = font_mid.render(map_config["name"], True, WHITE)
            screen.blit(name_text, (150, y+3))
            
            diff_text = font_tiny.render(f"难度: {map_config['difficulty']}", True, GOLD)
            screen.blit(diff_text, (150, y+33))
            
            desc_text = font_tiny.render(map_config["desc"], True, GRAY)
            screen.blit(desc_text, (350, y+8))
            
            if selected:
                status = "✅ 已选"
                status_color = GREEN
            elif unlocked:
                status = "✓ 可用"
                status_color = GRAY
            else:
                status = "🔒 未解锁"
                status_color = RED
            
            status_label = font_small.render(status, True, status_color)
            screen.blit(status_label, (350, y+31))
            
            btn_x, btn_y = 530, y+13
            btn_w, btn_h = 100, 35
            
            mouse = pygame.mouse.get_pos()
            click = pygame.mouse.get_pressed()[0]
            
            if selected:
                self.draw_button(screen, "已选", btn_x, btn_y, btn_w, btn_h, GREEN)
            elif unlocked:
                if btn_x < mouse[0] < btn_x+btn_w and btn_y < mouse[1] < btn_y+btn_h:
                    self.draw_button(screen, "选择", btn_x, btn_y, btn_w, btn_h, BLUE)
                    if click:
                        self.selected_map = map_id
                        self.background = Background(map_id)
                else:
                    self.draw_button(screen, "选择", btn_x, btn_y, btn_w, btn_h, (60, 60, 80))
            
            y += 85
        
        self.draw_button(screen, "ESC 返回", WIDTH//2-80, HEIGHT-60, 160, 40, (60, 60, 80))
    
    def draw_game(self):
        self.background.draw(screen)
        
        for obs in self.obstacles:
            obs.draw(screen)
        
        for coin in self.coins:
            coin.draw(screen)
        
        for p in self.particles:
            p.draw(screen)
        
        self.player.draw(screen)
        
        hud_y = 10
        
        time_text = font_small.render(f"⏱️ {self.time//60}s", True, WHITE)
        screen.blit(time_text, (10, hud_y))
        
        score_text = font_small.render(f"⭐ {self.score}", True, GOLD)
        screen.blit(score_text, (WIDTH//2 - 30, hud_y))
        
        coin_text = font_small.render(f"💰 {self.coins_collected}", True, GOLD)
        screen.blit(coin_text, (WIDTH//2 + 60, hud_y))
        
        if self.combo >= 3:
            combo_text = font_small.render(f"🔥 x{self.combo}", True, ORANGE)
            screen.blit(combo_text, (WIDTH//2 + 140, hud_y))
        
        diff_text = font_small.render(f"Lv.{self.difficulty}", True, RED if self.difficulty > 5 else WHITE)
        screen.blit(diff_text, (WIDTH-120, hud_y))
        
        if self.player.shield > 0:
            shield_text = font_small.render(f"🛡️ {self.player.shield}", True, CYAN)
            screen.blit(shield_text, (WIDTH-200, hud_y))
        
        pause_text = font_tiny.render("P暂停  S存档", True, GRAY)
        screen.blit(pause_text, (WIDTH-100, hud_y))
    
    def draw_pause(self):
        overlay = pygame.Surface((WIDTH, HEIGHT))
        overlay.set_alpha(160)
        overlay.fill(BLACK)
        screen.blit(overlay, (0, 0))
        
        pause_text = font_big.render("⏸️ 暂停", True, WHITE)
        screen.blit(pause_text, (WIDTH//2 - pause_text.get_width()//2, HEIGHT//2 - 80))
        
        hints = [
            "P 继续游戏",
            "S 保存进度",
            "Q 返回菜单"
        ]
        y = HEIGHT//2 - 10
        for hint in hints:
            hint_label = font_mid.render(hint, True, GRAY)
            screen.blit(hint_label, (WIDTH//2 - hint_label.get_width()//2, y))
            y += 40
    
    def draw_game_over(self):
        overlay = pygame.Surface((WIDTH, HEIGHT))
        overlay.set_alpha(180)
        overlay.fill(BLACK)
        screen.blit(overlay, (0, 0))
        
        over_text = font_huge.render("💥 坠毁", True, RED)
        screen.blit(over_text, (WIDTH//2 - over_text.get_width()//2, HEIGHT//2 - 130))
        
        stats = [
            f"⭐ 得分: {self.score}",
            f"💰 本局金币: +{self.coins_collected}",
            f"💰 总金币: {self.total_coins}",
            f"⏱️ 生存: {self.time//60}秒",
            f"🔥 最大连击: {self.max_combo}",
            f"🏆 最高纪录: {max(self.high_score, self.score)}",
        ]
        
        y = HEIGHT//2 - 50
        for stat in stats:
            label = font_mid.render(stat, True, WHITE)
            screen.blit(label, (WIDTH//2 - label.get_width()//2, y))
            y += 40
        
        hint = font_mid.render("按空格返回菜单", True, GRAY)
        screen.blit(hint, (WIDTH//2 - hint.get_width()//2, HEIGHT//2 + 120))
    
    def run(self):
        running = True
        while running:
            running = self.handle_events()
            self.update()
            
            screen.fill(DARK)
            
            if self.state == "menu":
                self.draw_menu()
            elif self.state == "playing":
                self.draw_game()
            elif self.state == "paused":
                self.draw_game()
                self.draw_pause()
            elif self.state == "game_over":
                self.draw_game()
                self.draw_game_over()
            elif self.state == "shop":
                self.draw_shop()
            elif self.state == "map_select":
                self.draw_map_select()
            
            pygame.display.flip()
            clock.tick(FPS)
        
        pygame.quit()

if __name__ == "__main__":
    game = Game()
    game.run()