import pygame
import sys
import random
import math
from pygame import gfxdraw

# 初始化pygame
pygame.init()

# 游戏窗口设置
SCREEN_WIDTH = 1200
SCREEN_HEIGHT = 800
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("极速飞车 - 豪华版")
clock = pygame.time.Clock()
FPS = 60

# 颜色定义
SKY_BLUE = (135, 206, 235)
SKY_LIGHT = (176, 226, 255)
CLOUD_WHITE = (255, 255, 255)
GRASS_DARK = (60, 150, 60)
GRASS_LIGHT = (90, 180, 90)
TRACK_GRAY = (100, 100, 100)
TRACK_LINE = (255, 255, 255)
TRACK_EDGE = (80, 80, 80)
TEXT_WHITE = (255, 255, 255)
TEXT_BLACK = (0, 0, 0)
TEXT_RED = (255, 50, 50)
TEXT_BLUE = (30, 136, 229)
TEXT_GOLD = (255, 215, 0)
BUTTON_COLOR = (33, 150, 243)
BUTTON_HOVER = (66, 165, 245)
CAR_COLORS = [
    [(255, 50, 50), (200, 30, 30)],  # 红色
    [(50, 150, 255), (30, 100, 200)],  # 蓝色
    [(50, 200, 50), (30, 150, 30)],  # 绿色
    [(255, 215, 0), (200, 170, 0)],  # 金色
    [(180, 50, 255), (140, 30, 200)]  # 紫色
]

# 创建字体
def create_font(size):
    try:
        return pygame.font.Font(None, size)
    except:
        return pygame.font.SysFont('arial', size)

font_tiny = create_font(16)
font_small = create_font(24)
font_medium = create_font(36)
font_large = create_font(48)
font_huge = create_font(72)

# 高级粒子系统
class AdvancedParticle:
    def __init__(self, x, y, color, size=3, speed=2, life=60, particle_type="dust"):
        self.x = x
        self.y = y
        self.color = color
        self.size = size
        self.vx = random.uniform(-speed, speed)
        self.vy = random.uniform(-speed, speed)
        self.life = life
        self.max_life = life
        self.type = particle_type
        self.rotation = random.uniform(0, 360)
        self.rotation_speed = random.uniform(-5, 5)
        self.glow_size = size * 3
        self.pulse_speed = random.uniform(0.05, 0.1)
        self.pulse = 0
        
    def update(self):
        self.x += self.vx
        self.y += self.vy
        
        if self.type == "dust":
            self.vy += 0.05
        elif self.type == "spark":
            self.vy -= 0.02
        elif self.type == "smoke":
            self.vy -= 0.1
            self.vx *= 0.98
        
        self.life -= 1
        self.size = max(0, self.size - 0.05)
        self.rotation += self.rotation_speed
        self.pulse = (self.pulse + self.pulse_speed) % (2 * math.pi)
        
    def draw(self, surface):
        if self.life > 0:
            alpha = int(255 * (self.life / self.max_life))
            
            if self.type in ["spark", "glow"]:
                # 绘制发光效果
                glow_alpha = alpha // 3
                for i in range(3, 0, -1):
                    glow_size = self.glow_size * (i / 3)
                    glow_color = (*self.color[:3], glow_alpha)
                    pygame.draw.circle(surface, glow_color, 
                                     (int(self.x), int(self.y)), int(glow_size))
            
            if self.type == "spark":
                # 星形粒子
                points = []
                for i in range(5):
                    angle = self.rotation + i * 72
                    radius = self.size * (1 + math.sin(self.pulse) * 0.3)
                    px = self.x + math.cos(math.radians(angle)) * radius
                    py = self.y + math.sin(math.radians(angle)) * radius
                    points.append((px, py))
                
                particle_color = (*self.color[:3], alpha)
                pygame.draw.polygon(surface, particle_color, points)
                
            elif self.type == "smoke":
                # 烟雾效果
                smoke_color = (*self.color[:3], alpha)
                pygame.draw.circle(surface, smoke_color, 
                                 (int(self.x), int(self.y)), int(self.size))
                
            else:
                # 普通粒子
                particle_color = (*self.color[:3], alpha)
                pygame.draw.circle(surface, particle_color, 
                                 (int(self.x), int(self.y)), int(self.size))
            
    def is_alive(self):
        return self.life > 0

# 动态云朵
class DynamicCloud:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.speed = random.uniform(0.5, 2.0)
        self.size = random.randint(80, 150)
        self.opacity = random.randint(150, 220)
        self.time = random.uniform(0, 10)
        self.pulse_speed = random.uniform(0.01, 0.03)
        self.pulse = 0
        
    def update(self):
        self.x += self.speed
        self.time += 0.01
        self.pulse = (self.pulse + self.pulse_speed) % (2 * math.pi)
        self.y += math.sin(self.time) * 0.5
        
        if self.x > SCREEN_WIDTH + self.size:
            self.x = -self.size
            self.y = random.randint(50, 200)
            self.size = random.randint(80, 150)
            
    def draw(self, surface):
        cloud_surface = pygame.Surface((self.size*2, self.size), pygame.SRCALPHA)
        
        # 云朵脉动
        pulse_scale = 1 + math.sin(self.pulse) * 0.1
        current_size = int(self.size * pulse_scale)
        
        # 绘制多层云朵
        for i in range(3, 0, -1):
            layer_size = current_size * (i / 3)
            layer_opacity = self.opacity * (i / 3)
            
            # 云朵主体
            pygame.draw.ellipse(cloud_surface, 
                              (*CLOUD_WHITE, int(layer_opacity)), 
                              (self.size - layer_size, 
                               self.size//2 - layer_size//3, 
                               layer_size*2, layer_size//1.5))
            
            # 云朵细节
            offsets = [-layer_size//3, 0, layer_size//3, layer_size*2//3]
            for offset in offsets:
                pygame.draw.circle(cloud_surface, 
                                 (*CLOUD_WHITE, int(layer_opacity)), 
                                 (self.size + offset, self.size//2), 
                                 layer_size//2)
        
        surface.blit(cloud_surface, (int(self.x), int(self.y)))

# 光照效果
class LightEffect:
    def __init__(self, x, y, radius=100, intensity=0.3):
        self.x = x
        self.y = y
        self.radius = radius
        self.intensity = intensity
        self.time = random.uniform(0, 10)
        
    def update(self):
        self.time += 0.02
        
    def draw(self, surface, camera_x):
        # 创建光照表面
        light_surface = pygame.Surface((self.radius*2, self.radius*2), pygame.SRCALPHA)
        
        # 计算脉动
        pulse = 1 + math.sin(self.time) * 0.1
        current_radius = int(self.radius * pulse)
        
        # 创建径向渐变
        for r in range(current_radius, 0, -2):
            alpha = int(self.intensity * 255 * (1 - r/current_radius))
            color = (255, 255, 200, alpha)
            pygame.draw.circle(light_surface, color, 
                             (current_radius, current_radius), r)
        
        # 绘制到主表面
        surface.blit(light_surface, 
                    (int(self.x - current_radius - camera_x), 
                     int(self.y - current_radius)))
        
# 高级赛道类
class PremiumTrack:
    def __init__(self, track_type=1):
        self.track_type = track_type
        self.track_width = 4000
        self.track_points = []
        self.inner_points = []
        self.outer_points = []
        self.checkpoints = []
        self.lights = []
        self.track_surface = None
        self.grass_surface = None
        self.generate_track()
        self.generate_graphics()
        
    def generate_track(self):
        """生成随机赛道"""
        self.track_points = []
        self.inner_points = []
        self.outer_points = []
        
        # 赛道参数
        base_y = SCREEN_HEIGHT // 2
        track_width = 200
        
        for x in range(0, self.track_width, 5):
            y = base_y
            
            # 根据赛道类型添加不同的曲线
            if self.track_type == 1:  # 山路
                y += math.sin(x * 0.003) * 120
                y += math.sin(x * 0.007) * 60
                y += math.cos(x * 0.001) * 40
            elif self.track_type == 2:  # 沙漠
                y += math.sin(x * 0.002) * 100
                y += math.cos(x * 0.005) * 80
                y += math.sin(x * 0.008) * 30
            elif self.track_type == 3:  # 城市
                y += math.sin(x * 0.0025) * 80
                y += math.cos(x * 0.006) * 50
                
            # 添加随机起伏
            y += random.uniform(-5, 5)
            
            # 确保y在合理范围内
            y = max(200, min(SCREEN_HEIGHT - 200, y))
            
            self.track_points.append((x, y))
            
            # 生成内圈和外圈
            angle = 0
            if len(self.track_points) > 1:
                prev_point = self.track_points[-2]
                dx = x - prev_point[0]
                dy = y - prev_point[1]
                angle = math.atan2(dy, dx)
            
            # 内圈点
            inner_x = x - math.sin(angle) * track_width
            inner_y = y + math.cos(angle) * track_width
            self.inner_points.append((inner_x, inner_y))
            
            # 外圈点
            outer_x = x + math.sin(angle) * track_width
            outer_y = y - math.cos(angle) * track_width
            self.outer_points.append((outer_x, outer_y))
        
        # 生成检查点
        self.generate_checkpoints()
        
        # 生成路灯
        self.generate_lights()
        
    def generate_checkpoints(self):
        """生成检查点"""
        checkpoint_spacing = 400
        for i in range(0, len(self.track_points), checkpoint_spacing):
            if i < len(self.track_points):
                x, y = self.track_points[i]
                self.checkpoints.append({
                    'x': x,
                    'y': y,
                    'radius': 40,
                    'checked': False,
                    'light': LightEffect(x, y, 60, 0.4)
                })
        
    def generate_lights(self):
        """生成路灯"""
        light_spacing = 300
        for i in range(0, len(self.track_points), light_spacing):
            if i < len(self.track_points):
                x, y = self.track_points[i]
                # 在赛道两侧放置路灯
                for side in [-1, 1]:
                    light_x = x + side * 150
                    light_y = y
                    self.lights.append(LightEffect(light_x, light_y, 80, 0.2))
                    
    def generate_graphics(self):
        """生成赛道图形"""
        self.track_surface = pygame.Surface((self.track_width, SCREEN_HEIGHT), pygame.SRCALPHA)
        self.grass_surface = pygame.Surface((self.track_width, SCREEN_HEIGHT), pygame.SRCALPHA)
        
        # 绘制草地
        for y in range(SCREEN_HEIGHT):
            t = y / SCREEN_HEIGHT
            r = int(GRASS_DARK[0] + t * (GRASS_LIGHT[0] - GRASS_DARK[0]))
            g = int(GRASS_DARK[1] + t * (GRASS_LIGHT[1] - GRASS_DARK[1]))
            b = int(GRASS_DARK[2] + t * (GRASS_LIGHT[2] - GRASS_DARK[2]))
            # 确保颜色值有效
            r = max(0, min(255, r))
            g = max(0, min(255, g))
            b = max(0, min(255, b))
            pygame.draw.line(self.grass_surface, (r, g, b), 
                           (0, y), (self.track_width, y))
        
        # 绘制赛道
        for i in range(len(self.inner_points) - 1):
            # 获取四个点
            inner_x1, inner_y1 = self.inner_points[i]
            inner_x2, inner_y2 = self.inner_points[i+1]
            outer_x1, outer_y1 = self.outer_points[i]
            outer_x2, outer_y2 = self.outer_points[i+1]
            
            # 创建赛道段表面
            segment_width = max(abs(outer_x1 - inner_x1), abs(outer_x2 - inner_x2)) + 10
            segment_height = max(abs(outer_y1 - inner_y1), abs(outer_y2 - inner_y2)) + 10
            segment_surface = pygame.Surface((int(segment_width), int(segment_height)), pygame.SRCALPHA)
            
            # 在局部坐标系中绘制
            offset_x = min(inner_x1, outer_x1, inner_x2, outer_x2) - 5
            offset_y = min(inner_y1, outer_y1, inner_y2, outer_y2) - 5
            
            # 转换坐标
            points = [
                (inner_x1 - offset_x, inner_y1 - offset_y),
                (inner_x2 - offset_x, inner_y2 - offset_y),
                (outer_x2 - offset_x, outer_y2 - offset_y),
                (outer_x1 - offset_x, outer_y1 - offset_y)
            ]
            
            # 绘制赛道
            pygame.draw.polygon(segment_surface, TRACK_GRAY, points)
            
            # 赛道边缘
            pygame.draw.polygon(segment_surface, TRACK_EDGE, points, 3)
            
            # 赛道中线
            center_x1 = (inner_x1 + outer_x1) / 2
            center_y1 = (inner_y1 + outer_y1) / 2
            center_x2 = (inner_x2 + outer_x2) / 2
            center_y2 = (inner_y2 + outer_y2) / 2
            
            pygame.draw.line(segment_surface, TRACK_LINE,
                           (center_x1 - offset_x, center_y1 - offset_y),
                           (center_x2 - offset_x, center_y2 - offset_y), 5)
            
            # 虚线
            if i % 20 < 10:
                pygame.draw.line(segment_surface, TRACK_LINE,
                               (center_x1 - offset_x, center_y1 - offset_y),
                               (center_x2 - offset_x, center_y2 - offset_y), 3)
            
            # 合并到主表面
            self.track_surface.blit(segment_surface, (int(offset_x), int(offset_y)))
                    
    def draw(self, surface, camera_x):
        """绘制赛道"""
        # 绘制草地背景
        surface.blit(self.grass_surface, (-camera_x, 0))
        
        # 绘制赛道
        surface.blit(self.track_surface, (-camera_x, 0))
        
        # 绘制光照效果
        for light in self.lights:
            light.update()
            if -100 < light.x - camera_x < SCREEN_WIDTH + 100:
                light.draw(surface, camera_x)
                
        # 绘制检查点
        for checkpoint in self.checkpoints:
            checkpoint_x = checkpoint['x'] - camera_x
            checkpoint_y = checkpoint['y']
            
            if 0 <= checkpoint_x <= SCREEN_WIDTH:
                # 检查点光效
                checkpoint['light'].update()
                checkpoint['light'].draw(surface, camera_x)
                
                # 检查点圆圈
                color = (50, 200, 50) if checkpoint['checked'] else (200, 200, 200)
                pygame.draw.circle(surface, color, 
                                 (int(checkpoint_x), int(checkpoint_y)), 30, 4)
                
                # 检查点编号
                checkpoint_index = self.checkpoints.index(checkpoint) + 1
                number_text = font_medium.render(str(checkpoint_index), True, color)
                text_rect = number_text.get_rect(center=(checkpoint_x, checkpoint_y))
                
                # 文字背景
                pygame.draw.rect(surface, (0, 0, 0, 150),
                               (text_rect.x-5, text_rect.y-3,
                                text_rect.width+10, text_rect.height+6),
                               border_radius=3)
                
                surface.blit(number_text, text_rect)

# 高级赛车类
class PremiumCar:
    def __init__(self, x, y, color_index=0, player_id=1):
        self.x = x
        self.y = y
        self.width = 60
        self.height = 30
        self.vx = 0
        self.vy = 0
        self.angle = 0
        self.angular_velocity = 0
        self.speed = 0
        self.max_speed = 20
        self.acceleration = 0.4
        self.deceleration = 0.3
        self.turn_speed = 0.06
        self.color_scheme = CAR_COLORS[color_index % len(CAR_COLORS)]
        self.player_id = player_id
        self.on_track = True
        self.trail = []
        self.trail_length = 20
        self.wheel_rotation = 0
        self.health = 100
        self.damage_timer = 0
        self.nitro = 100
        self.max_nitro = 100
        self.boost_active = False
        self.boost_timer = 0
        self.particles = []
        self.skid_marks = []
        self.last_checkpoint = 0
        self.lap = 1
        self.finish_time = 0
        self.headlight = LightEffect(x, y, 150, 0.5)
        self.exhaust_light = LightEffect(x, y, 50, 0.3)
        self.reflection_angle = 0
        
    def update(self, track, keys):
        """更新赛车状态"""
        # 保存轨迹
        self.trail.append((self.x, self.y, self.angle, self.speed))
        if len(self.trail) > self.trail_length:
            self.trail.pop(0)
            
        # 物理参数
        track_friction = 0.96
        off_track_slowdown = 0.6 if not self.on_track else 1.0
        
        # 控制输入
        if self.player_id == 1:  # 玩家控制
            if keys[pygame.K_UP]:
                self.speed += self.acceleration * off_track_slowdown
                # 排气粒子
                if random.random() < 0.3:
                    self.create_exhaust_particles()
            elif keys[pygame.K_DOWN]:
                self.speed -= self.acceleration * 2.0
                # 刹车火花
                if abs(self.speed) > 5 and random.random() < 0.2:
                    self.create_brake_sparks()
            else:
                # 自然减速
                if self.speed > 0:
                    self.speed -= self.deceleration
                elif self.speed < 0:
                    self.speed += self.deceleration
                    
            if keys[pygame.K_LEFT]:
                self.angular_velocity -= self.turn_speed * (1 - abs(self.speed)/self.max_speed)
                self.create_skid_particles()
            elif keys[pygame.K_RIGHT]:
                self.angular_velocity += self.turn_speed * (1 - abs(self.speed)/self.max_speed)
                self.create_skid_particles()
                
            if keys[pygame.K_SPACE] and self.nitro > 0 and self.speed > 0:
                self.activate_nitro()
                
        # 限制速度
        self.speed = max(-self.max_speed * 0.5, min(self.max_speed, self.speed))
        
        # 应用转向
        self.angle += self.angular_velocity * (abs(self.speed) / self.max_speed)
        self.angular_velocity *= 0.85
        
        # 氮气计时器
        if self.boost_timer > 0:
            self.boost_timer -= 1
        else:
            self.boost_active = False
            
        # 恢复氮气
        if not self.boost_active and self.nitro < self.max_nitro:
            self.nitro += 0.3
            
        # 计算速度分量
        self.vx = math.cos(self.angle) * self.speed
        self.vy = math.sin(self.angle) * self.speed
        
        # 应用摩擦
        self.vx *= track_friction
        self.vy *= track_friction
        self.speed = math.sqrt(self.vx**2 + self.vy**2) * (1 if self.vx > 0 else -1)
        
        # 车轮旋转
        self.wheel_rotation += self.speed * 0.2
        
        # 更新位置
        self.x += self.vx
        self.y += self.vy
        
        # 漂移痕迹
        if abs(self.angular_velocity) > 0.03 and self.speed > 4 and self.on_track:
            self.skid_marks.append({
                'x': self.x,
                'y': self.y,
                'angle': self.angle + math.pi/2,
                'life': 400,
                'width': 8 + abs(self.angular_velocity) * 20
            })
            
        # 更新光照位置
        self.headlight.x = self.x - math.cos(self.angle) * 20
        self.headlight.y = self.y - math.sin(self.angle) * 20
        
        self.exhaust_light.x = self.x + math.cos(self.angle) * 25
        self.exhaust_light.y = self.y + math.sin(self.angle) * 25
        
        # 更新粒子
        for particle in self.particles[:]:
            particle.update()
            if not particle.is_alive():
                self.particles.remove(particle)
                
        # 更新漂移痕迹
        for skid in self.skid_marks[:]:
            skid['life'] -= 2
            if skid['life'] <= 0:
                self.skid_marks.remove(skid)
                
        # 更新伤害计时器
        if self.damage_timer > 0:
            self.damage_timer -= 1
            
        # 反射角度动画
        self.reflection_angle = (self.reflection_angle + 0.02) % (2 * math.pi)
        
    def create_exhaust_particles(self):
        """创建排气粒子"""
        for _ in range(2):
            angle = self.angle + math.pi + random.uniform(-0.1, 0.1)
            speed = random.uniform(1, 3)
            particle_x = self.x + math.cos(self.angle) * 25
            particle_y = self.y + math.sin(self.angle) * 25
            
            self.particles.append(AdvancedParticle(
                particle_x, particle_y,
                (100, 100, 100), 4, speed, 40, "smoke"
            ))
            
    def create_brake_sparks(self):
        """创建刹车火花"""
        for _ in range(3):
            angle = self.angle + math.pi + random.uniform(-0.3, 0.3)
            speed = random.uniform(2, 5)
            particle_x = self.x - math.cos(self.angle) * 15
            particle_y = self.y - math.sin(self.angle) * 15
            
            self.particles.append(AdvancedParticle(
                particle_x, particle_y,
                (255, 200, 100), 3, speed, 25, "spark"
            ))
            
    def create_skid_particles(self):
        """创建漂移粒子"""
        if abs(self.angular_velocity) > 0.05 and self.speed > 3:
            for _ in range(2):
                side = 1 if self.angular_velocity > 0 else -1
                angle = self.angle + side * math.pi/2 + random.uniform(-0.2, 0.2)
                speed = random.uniform(1, 3)
                offset_x = math.cos(self.angle + side * math.pi/2) * 15
                offset_y = math.sin(self.angle + side * math.pi/2) * 15
                
                self.particles.append(AdvancedParticle(
                    self.x + offset_x, self.y + offset_y,
                    (150, 150, 150), 2, speed, 30, "dust"
                ))
                
    def activate_nitro(self):
        """激活氮气"""
        self.boost_active = True
        self.nitro = max(0, self.nitro - 2)
        self.boost_timer = 8
        
        # 氮气加速
        self.speed += 0.8
        
        # 氮气粒子
        for _ in range(5):
            angle = self.angle + math.pi + random.uniform(-0.2, 0.2)
            speed = random.uniform(4, 8)
            particle_x = self.x + math.cos(self.angle) * 25
            particle_y = self.y + math.sin(self.angle) * 25
            
            self.particles.append(AdvancedParticle(
                particle_x, particle_y,
                (100, 200, 255), 6, speed, 35, "spark"
            ))
            
    def draw_trail(self, surface, camera_x):
        """绘制轨迹"""
        for i, (trail_x, trail_y, trail_angle, trail_speed) in enumerate(self.trail):
            alpha = int(255 * (i / len(self.trail)) * 0.7)
            size = 3 * (i / len(self.trail))
            speed_factor = abs(trail_speed) / self.max_speed
            
            # 根据速度改变颜色
            if speed_factor > 0.7:
                trail_color = (255, 100, 100, alpha)  # 高速红色
            elif speed_factor > 0.4:
                trail_color = (255, 200, 100, alpha)  # 中速黄色
            else:
                trail_color = (200, 200, 200, alpha)  # 低速灰色
            
            # 绘制轨迹点
            pygame.draw.circle(surface, trail_color, 
                             (int(trail_x - camera_x), int(trail_y)), int(size))
            
    def draw_skid_marks(self, surface, camera_x):
        """绘制漂移痕迹"""
        for skid in self.skid_marks:
            alpha = int(255 * (skid['life'] / 400))
            width = int(skid['width'] * (skid['life'] / 400))
            length = 20
            
            # 创建漂移痕迹表面
            skid_surface = pygame.Surface((length*2, width*2), pygame.SRCALPHA)
            
            # 漂移痕迹颜色
            skid_color = (100, 100, 100, alpha)
            
            # 绘制漂移痕迹
            points = [
                (-length, -width//2),
                (length, -width//2),
                (length, width//2),
                (-length, width//2)
            ]
            
            # 转换到局部坐标系
            transformed_points = []
            for px, py in points:
                rotated_x = px * math.cos(skid['angle']) - py * math.sin(skid['angle'])
                rotated_y = px * math.sin(skid['angle']) + py * math.cos(skid['angle'])
                transformed_points.append((rotated_x + length, rotated_y + width))
            
            pygame.draw.polygon(skid_surface, skid_color, transformed_points)
            
            # 绘制到主表面
            surface.blit(skid_surface, 
                        (int(skid['x'] - length - camera_x),
                         int(skid['y'] - width)))
            
    def draw(self, surface, camera_x):
        """绘制赛车"""
        screen_x = self.x - camera_x
        screen_y = self.y
        
        # 绘制前灯光照
        if self.speed > 0:
            self.headlight.draw(surface, camera_x)
            
        # 绘制排气光照
        if self.boost_active:
            self.exhaust_light.intensity = 0.6
        else:
            self.exhaust_light.intensity = 0.3
        self.exhaust_light.draw(surface, camera_x)
        
        # 绘制漂移痕迹
        self.draw_skid_marks(surface, camera_x)
        
        # 绘制轨迹
        self.draw_trail(surface, camera_x)
        
        # 绘制粒子
        for particle in self.particles:
            particle.draw(surface)
            
        # 创建赛车表面
        car_surface = pygame.Surface((80, 50), pygame.SRCALPHA)
        
        # 车体 - 流线型设计
        car_points = [
            (10, 15),   # 左前
            (70, 15),   # 右前
            (75, 25),   # 右中
            (70, 35),   # 右后
            (10, 35),   # 左后
            (5, 25)     # 左中
        ]
        
        # 车体渐变色
        for i in range(len(car_points)-1):
            p1 = car_points[i]
            p2 = car_points[i+1]
            
            # 计算渐变色
            t1 = i / len(car_points)
            t2 = (i+1) / len(car_points)
            
            color1 = [
                int(self.color_scheme[0][j] + t1 * (self.color_scheme[1][j] - self.color_scheme[0][j]))
                for j in range(3)
            ]
            color2 = [
                int(self.color_scheme[0][j] + t2 * (self.color_scheme[1][j] - self.color_scheme[0][j]))
                for j in range(3)
            ]
            
            # 确保颜色值有效
            for j in range(3):
                color1[j] = max(0, min(255, color1[j]))
                color2[j] = max(0, min(255, color2[j]))
            
            pygame.draw.line(car_surface, color1, p1, p2, 8)
            pygame.draw.line(car_surface, color2, p1, p2, 8)
            
        # 车窗
        window_points = [
            (20, 18),
            (60, 18),
            (63, 25),
            (60, 32),
            (20, 32),
            (17, 25)
        ]
        pygame.draw.polygon(car_surface, (30, 40, 50, 180), window_points)
        
        # 车窗反射
        reflection_points = []
        for i, (wx, wy) in enumerate(window_points):
            offset = math.sin(self.reflection_angle + i * 0.5) * 2
            reflection_points.append((wx + offset, wy + offset))
        pygame.draw.polygon(car_surface, (255, 255, 255, 60), reflection_points)
        
        # 前大灯
        pygame.draw.ellipse(car_surface, (255, 255, 200), (5, 20, 10, 6))
        
        # 尾灯
        if self.speed < 0 or (hasattr(self, '_braking') and self._braking):
            brake_color = (255, 50, 50)
        else:
            brake_color = (200, 30, 30)
        pygame.draw.ellipse(car_surface, brake_color, (65, 20, 10, 6))
        
        # 车轮
        wheel_radius = 10
        front_wheel = (60, 25)
        rear_wheel = (20, 25)
        
        # 前轮
        pygame.draw.circle(car_surface, (20, 20, 20), front_wheel, wheel_radius)
        pygame.draw.circle(car_surface, (60, 60, 60), front_wheel, wheel_radius-3)
        
        # 车轮辐条
        for i in range(6):
            angle = self.wheel_rotation + i * 60
            radius = wheel_radius - 4
            x1 = front_wheel[0] + math.cos(math.radians(angle)) * radius
            y1 = front_wheel[1] + math.sin(math.radians(angle)) * radius
            x2 = front_wheel[0] - math.cos(math.radians(angle)) * radius
            y2 = front_wheel[1] - math.sin(math.radians(angle)) * radius
            pygame.draw.line(car_surface, (150, 150, 150), (x1, y1), (x2, y2), 3)
            
        # 后轮
        pygame.draw.circle(car_surface, (20, 20, 20), rear_wheel, wheel_radius)
        pygame.draw.circle(car_surface, (60, 60, 60), rear_wheel, wheel_radius-3)
        
        # 车轮辐条
        for i in range(6):
            angle = self.wheel_rotation + i * 60
            radius = wheel_radius - 4
            x1 = rear_wheel[0] + math.cos(math.radians(angle)) * radius
            y1 = rear_wheel[1] + math.sin(math.radians(angle)) * radius
            x2 = rear_wheel[0] - math.cos(math.radians(angle)) * radius
            y2 = rear_wheel[1] - math.sin(math.radians(angle)) * radius
            pygame.draw.line(car_surface, (150, 150, 150), (x1, y1), (x2, y2), 3)
        
        # 车牌
        pygame.draw.rect(car_surface, (200, 200, 200), (35, 28, 20, 10))
        plate_text = font_tiny.render(str(self.player_id), True, (0, 0, 0))
        car_surface.blit(plate_text, (40, 30))
        
        # 旋转赛车
        rotated_car = pygame.transform.rotate(car_surface, math.degrees(-self.angle))
        
        # 赛车阴影
        shadow = rotated_car.copy()
        shadow.fill((0, 0, 0, 100), None, pygame.BLEND_RGBA_MULT)
        surface.blit(shadow, 
                    (screen_x - rotated_car.get_width()//2 + 3, 
                     screen_y - rotated_car.get_height()//2 + 3))
        
        # 绘制赛车
        surface.blit(rotated_car, 
                    (screen_x - rotated_car.get_width()//2, 
                     screen_y - rotated_car.get_height()//2))
        
        # 氮气效果
        if self.boost_active:
            self.draw_nitro_effect(surface, screen_x, screen_y)
            
        # 绘制状态条
        self.draw_status_bars(surface, screen_x, screen_y)
        
    def draw_nitro_effect(self, surface, x, y):
        """绘制氮气效果"""
        nitro_surface = pygame.Surface((100, 100), pygame.SRCALPHA)
        
        # 多层脉动光晕
        for i in range(4, 0, -1):
            size = 20 + i * 10
            alpha = 150 - i * 30
            pulse = 1 + math.sin(pygame.time.get_ticks() * 0.01 + i) * 0.2
            
            # 径向渐变
            for r in range(int(size * pulse), 0, -2):
                current_alpha = int(alpha * (1 - r/(size * pulse)))
                color = (100, 200, 255, current_alpha)
                pygame.draw.circle(nitro_surface, color, (50, 50), r)
        
        # 绘制到主表面
        surface.blit(nitro_surface, (x - 50, y - 50))
            
    def draw_status_bars(self, surface, x, y):
        """绘制状态条"""
        bar_width = 60
        bar_height = 8
        spacing = 12
        
        # 氮气条
        nitro_x = x - bar_width//2
        nitro_y = y - 80
        
        # 背景
        pygame.draw.rect(surface, (30, 30, 50), 
                        (nitro_x, nitro_y, bar_width, bar_height), border_radius=4)
        
        # 氮气填充
        nitro_fill = int(bar_width * (self.nitro / self.max_nitro))
        
        # 渐变填充
        for i in range(nitro_fill):
            t = i / bar_width
            r = int(100 + 155 * (1 - t))
            g = int(100 + 155 * t)
            b = 255
            # 确保颜色值有效
            r = max(0, min(255, r))
            g = max(0, min(255, g))
            b = max(0, min(255, b))
            pygame.draw.line(surface, (r, g, b), 
                           (nitro_x + i, nitro_y), 
                           (nitro_x + i, nitro_y + bar_height))
        
        # 边框
        pygame.draw.rect(surface, (200, 200, 255), 
                        (nitro_x, nitro_y, bar_width, bar_height), 1, border_radius=4)
        
        # 生命条
        health_x = x - bar_width//2
        health_y = y - 80 - spacing
        
        # 背景
        pygame.draw.rect(surface, (50, 30, 30), 
                        (health_x, health_y, bar_width, bar_height), border_radius=4)
        
        # 生命填充
        health_fill = int(bar_width * (self.health / 100))
        
        # 渐变填充
        for i in range(health_fill):
            t = i / bar_width
            r = int(255 * (1 - t))
            g = int(255 * t)
            b = 0
            # 确保颜色值有效
            r = max(0, min(255, r))
            g = max(0, min(255, g))
            b = max(0, min(255, b))
            pygame.draw.line(surface, (r, g, b), 
                           (health_x + i, health_y), 
                           (health_x + i, health_y + bar_height))
        
        # 边框
        pygame.draw.rect(surface, (255, 200, 200), 
                        (health_x, health_y, bar_width, bar_height), 1, border_radius=4)
        
        # 速度显示
        speed_text = font_medium.render(f"{abs(self.speed):.0f}", True, TEXT_WHITE)
        speed_shadow = font_medium.render(f"{abs(self.speed):.0f}", True, (0, 0, 0))
        
        # 速度背景
        speed_bg = pygame.Surface((speed_text.get_width()+10, speed_text.get_height()+6), pygame.SRCALPHA)
        pygame.draw.rect(speed_bg, (0, 0, 0, 150), 
                        (0, 0, speed_bg.get_width(), speed_bg.get_height()), border_radius=4)
        
        surface.blit(speed_bg, (x - speed_bg.get_width()//2, y - 120))
        surface.blit(speed_shadow, (x - speed_text.get_width()//2 + 2, y - 118))
        surface.blit(speed_text, (x - speed_text.get_width()//2, y - 120))

# 游戏主类
class PremiumRacingGame:
    def __init__(self):
        self.state = "menu"
        self.track_type = 1
        self.lap_count = 3
        self.current_lap = 1
        self.time = 0
        self.best_time = 0
        self.camera_x = 0
        self.track = None
        self.player_car = None
        self.ai_cars = []
        self.clouds = []
        self.sun_light = LightEffect(SCREEN_WIDTH//2, 100, 300, 0.2)
        
    def start_race(self):
        """开始比赛"""
        self.state = "playing"
        self.track = PremiumTrack(self.track_type)
        
        # 创建玩家赛车
        self.player_car = PremiumCar(200, SCREEN_HEIGHT//2, 0, 1)
        
        # 创建AI赛车
        self.ai_cars = []
        for i in range(3):
            ai_car = PremiumCar(300 + i*60, SCREEN_HEIGHT//2 - 80 + i*40, i+1, i+2)
            self.ai_cars.append(ai_car)
            
        self.camera_x = 0
        self.time = 0
        self.current_lap = 1
        
        # 创建云朵
        self.clouds = []
        for _ in range(10):
            x = random.randint(-300, SCREEN_WIDTH + 300)
            y = random.randint(50, 250)
            self.clouds.append(DynamicCloud(x, y))
            
    def update(self):
        """更新游戏状态"""
        if self.state == "playing":
            self.time += 1/60
            
            # 更新云朵
            for cloud in self.clouds:
                cloud.update()
                
            # 获取按键
            keys = pygame.key.get_pressed()
            
            # 更新赛车
            if self.player_car:
                self.player_car.update(self.track, keys)
                
            for ai_car in self.ai_cars:
                ai_car.update(self.track, {})
                
            # 更新相机
            if self.player_car:
                self.update_camera()
                
    def update_camera(self):
        """更新相机"""
        if self.player_car:
            target_x = self.player_car.x - SCREEN_WIDTH // 2
            self.camera_x += (target_x - self.camera_x) * 0.08
            
            # 限制范围
            if self.track:
                self.camera_x = max(0, min(self.camera_x, self.track.track_width - SCREEN_WIDTH))
                
    def draw_background(self, surface):
        """绘制背景"""
        # 天空渐变
        for y in range(SCREEN_HEIGHT):
            t = y / SCREEN_HEIGHT
            r = int(SKY_BLUE[0] + t * 60)
            g = int(SKY_BLUE[1] + t * 40)
            b = int(SKY_BLUE[2] + t * 30)
            
            # 边界检查
            r = max(0, min(255, r))
            g = max(0, min(255, g))
            b = max(0, min(255, b))
            
            pygame.draw.line(surface, (r, g, b), (0, y), (SCREEN_WIDTH, y))
            
        # 太阳光照
        self.sun_light.draw(surface, 0)
        
        # 远山
        for i in range(5):
            x = -self.camera_x * 0.2 + i * 300
            height = 200 + i * 40
            alpha = 100 + i * 20
            
            # 山体颜色
            mountain_color = (
                max(0, min(255, 80 - i*10)),
                max(0, min(255, 100 - i*10)),
                max(0, min(255, 120 - i*10))
            )
            
            # 创建山体表面
            mountain_surface = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
            points = [
                (x, SCREEN_HEIGHT - 150),
                (x + 150, SCREEN_HEIGHT - 150 - height),
                (x + 300, SCREEN_HEIGHT - 150)
            ]
            pygame.draw.polygon(mountain_surface, (*mountain_color, alpha), points)
            surface.blit(mountain_surface, (0, 0))
            
        # 云朵
        for cloud in self.clouds:
            cloud.draw(surface)
            
    def draw_game(self, surface):
        """绘制游戏"""
        # 绘制背景
        self.draw_background(surface)
        
        # 绘制赛道
        if self.track:
            self.track.draw(surface, self.camera_x)
            
        # 绘制AI赛车
        for ai_car in self.ai_cars:
            ai_car.draw(surface, self.camera_x)
            
        # 绘制玩家赛车
        if self.player_car:
            self.player_car.draw(surface, self.camera_x)
            
        # 绘制UI
        self.draw_game_ui(surface)
        
    def draw_game_ui(self, surface):
        """绘制游戏UI"""
        # 半透明面板
        panel = pygame.Surface((300, 160), pygame.SRCALPHA)
        pygame.draw.rect(panel, (0, 0, 0, 120), (0, 0, 300, 160), border_radius=15)
        pygame.draw.rect(panel, (255, 255, 255, 50), (0, 0, 300, 160), 2, border_radius=15)
        surface.blit(panel, (20, 20))
        
        if self.player_car:
            # 时间
            time_text = font_medium.render(f"时间: {self.time:.2f}s", True, TEXT_WHITE)
            surface.blit(time_text, (40, 40))
            
            # 圈数
            lap_text = font_medium.render(f"圈数: {self.player_car.lap}/{self.lap_count}", True, TEXT_WHITE)
            surface.blit(lap_text, (40, 80))
            
            # 速度
            speed_text = font_medium.render(f"速度: {abs(self.player_car.speed):.0f} km/h", True, TEXT_WHITE)
            surface.blit(speed_text, (40, 120))
            
            # 氮气
            nitro_text = font_medium.render(f"氮气: {int(self.player_car.nitro)}%", True, (100, 200, 255))
            surface.blit(nitro_text, (40, 160))
            
        # 控制提示
        controls = font_small.render("方向键: 移动 | 空格: 氮气 | ESC: 暂停", True, TEXT_WHITE)
        surface.blit(controls, (SCREEN_WIDTH//2 - controls.get_width()//2, SCREEN_HEIGHT - 40))
        
    def draw_menu(self, surface):
        """绘制菜单"""
        # 背景效果
        overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 100))
        surface.blit(overlay, (0, 0))
        
        # 游戏标题
        title = font_huge.render("极速飞车", True, (255, 50, 50))
        title_shadow = font_huge.render("极速飞车", True, (0, 0, 0, 150))
        
        # 标题光晕
        for i in range(4, 0, -1):
            glow_alpha = 60 - i * 10
            glow_surface = pygame.Surface((title.get_width()+i*30, title.get_height()+i*20), pygame.SRCALPHA)
            pygame.draw.rect(glow_surface, (255, 50, 50, glow_alpha), 
                           (0, 0, glow_surface.get_width(), glow_surface.get_height()), 
                           border_radius=20)
            surface.blit(glow_surface, 
                        (SCREEN_WIDTH//2 - glow_surface.get_width()//2, 
                         150 - i*5))
        
        surface.blit(title_shadow, (SCREEN_WIDTH//2 - title.get_width()//2 + 5, 155))
        surface.blit(title, (SCREEN_WIDTH//2 - title.get_width()//2, 150))
        
        # 赛道选择
        track_names = ["🏔️ 山路赛道", "🏜️ 沙漠赛道", "🏙️ 城市赛道"]
        track_text = font_large.render(track_names[self.track_type-1], True, TEXT_GOLD)
        surface.blit(track_text, (SCREEN_WIDTH//2 - track_text.get_width()//2, 250))
        
        # 开始按钮
        start_button = pygame.Rect(SCREEN_WIDTH//2 - 150, 350, 300, 80)
        pygame.draw.rect(surface, BUTTON_COLOR, start_button, border_radius=15)
        pygame.draw.rect(surface, (255, 255, 255, 150), start_button, 3, border_radius=15)
        
        start_text = font_large.render("🏁 开始比赛", True, TEXT_WHITE)
        surface.blit(start_text, (SCREEN_WIDTH//2 - start_text.get_width()//2, 375))
        
        # 控制说明
        instructions = [
            "控制说明:",
            "方向键 ↑↓: 加速/刹车",
            "方向键 ←→: 转向",
            "空格键: 氮气加速",
            "ESC: 暂停/菜单"
        ]
        
        for i, instruction in enumerate(instructions):
            inst_text = font_small.render(instruction, True, TEXT_WHITE)
            surface.blit(inst_text, (SCREEN_WIDTH//2 - inst_text.get_width()//2, 500 + i*30))
            
    def handle_events(self):
        """处理事件"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
                
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    if self.state == "playing":
                        self.state = "paused"
                    elif self.state == "paused":
                        self.state = "playing"
                    elif self.state == "menu":
                        self.track_type = (self.track_type % 3) + 1
                        
                elif event.key == pygame.K_RETURN and self.state == "menu":
                    self.start_race()
                    
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1 and self.state == "menu":
                    mouse_pos = pygame.mouse.get_pos()
                    start_button = pygame.Rect(SCREEN_WIDTH//2 - 150, 350, 300, 80)
                    if start_button.collidepoint(mouse_pos):
                        self.start_race()
                        
    def draw(self, surface):
        """绘制游戏"""
        if self.state == "menu":
            self.draw_menu(surface)
        elif self.state == "playing":
            self.draw_game(surface)
        elif self.state == "paused":
            self.draw_game(surface)
            # 暂停覆盖层
            overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
            overlay.fill((0, 0, 0, 150))
            surface.blit(overlay, (0, 0))
            
            pause_text = font_huge.render("比赛暂停", True, TEXT_GOLD)
            surface.blit(pause_text, (SCREEN_WIDTH//2 - pause_text.get_width()//2, 300))
            
            continue_text = font_medium.render("按 ESC 继续比赛", True, TEXT_WHITE)
            surface.blit(continue_text, (SCREEN_WIDTH//2 - continue_text.get_width()//2, 400))

def main():
    game = PremiumRacingGame()
    
    while True:
        game.handle_events()
        game.update()
        game.draw(screen)
        pygame.display.flip()
        clock.tick(FPS)

if __name__ == "__main__":
    main()