import pygame
import sys
import random
import math
from pygame.locals import *

# 初始化 Pygame
pygame.init()

# 游戏窗口设置
WIDTH, HEIGHT = 1000, 700
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("极速狂飙 - 赛车挑战")

# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 50, 50)
GREEN = (50, 255, 50)
BLUE = (50, 100, 255)
YELLOW = (255, 255, 50)
PURPLE = (180, 50, 230)
ORANGE = (255, 165, 0)
CYAN = (0, 255, 255)
GRAY = (100, 100, 100)
LIGHT_GRAY = (200, 200, 200)
DARK_GRAY = (50, 50, 50)
DARK_GREEN = (0, 100, 0)
GRASS_GREEN = (60, 180, 75)
ROAD_GRAY = (80, 80, 80)
ROAD_LINE = (255, 255, 200)
SKY_BLUE = (135, 206, 235)

# 加载字体
try:
    font_large = pygame.font.Font(None, 48)
    font_medium = pygame.font.Font(None, 36)
    font_small = pygame.font.Font(None, 24)
    font_tiny = pygame.font.Font(None, 20)
except:
    font_large = pygame.font.SysFont(None, 48)
    font_medium = pygame.font.SysFont(None, 36)
    font_small = pygame.font.SysFont(None, 24)
    font_tiny = pygame.font.SysFont(None, 20)

# 音效初始化
try:
    pygame.mixer.init()
    engine_sound = pygame.mixer.Sound(bytearray([random.randint(0, 255) for _ in range(50)]))
    crash_sound = pygame.mixer.Sound(bytearray([random.randint(0, 255) for _ in range(50)]))
    collect_sound = pygame.mixer.Sound(bytearray([random.randint(0, 255) for _ in range(50)]))
    victory_sound = pygame.mixer.Sound(bytearray([random.randint(0, 255) for _ in range(50)]))
    game_over_sound = pygame.mixer.Sound(bytearray([random.randint(0, 255) for _ in range(50)]))
    nitro_sound = pygame.mixer.Sound(bytearray([random.randint(0, 255) for _ in range(50)]))
except:
    class SilentSound:
        def play(self): pass
    engine_sound = SilentSound()
    crash_sound = SilentSound()
    collect_sound = SilentSound()
    victory_sound = SilentSound()
    game_over_sound = SilentSound()
    nitro_sound = SilentSound()

# 游戏参数
ROAD_WIDTH = 400
ROAD_MARGIN = 50
CAR_WIDTH = 40
CAR_HEIGHT = 70
OBSTACLE_WIDTH = 50
OBSTACLE_HEIGHT = 50
COIN_RADIUS = 15
NITRO_RADIUS = 20
FPS = 60

class Car:
    """赛车类"""
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.width = CAR_WIDTH
        self.height = CAR_HEIGHT
        self.speed = 0
        self.max_speed = 8
        self.acceleration = 0.2
        self.deceleration = 0.1
        self.brake_power = 0.3
        self.steering = 0
        self.max_steering = 3
        self.steering_speed = 0.1
        self.color = RED
        self.health = 100
        self.score = 0
        self.coins = 0
        self.nitro = 0
        self.max_nitro = 100
        self.nitro_active = False
        self.nitro_timer = 0
        self.drift_angle = 0
        self.skid_marks = []
        self.crash_timer = 0
        self.visible = True
        self.engine_sound_playing = False
        
    def update(self, keys, road_left, road_right):
        """更新赛车状态"""
        # 加速/减速
        if keys[K_UP] or keys[K_w]:
            self.speed = min(self.speed + self.acceleration, self.max_speed)
            if not self.engine_sound_playing:
                engine_sound.play(-1)  # 循环播放引擎声
                self.engine_sound_playing = True
        elif keys[K_DOWN] or keys[K_s]:
            self.speed = max(self.speed - self.brake_power, -self.max_speed/2)
        else:
            # 自然减速
            if self.speed > 0:
                self.speed = max(self.speed - self.deceleration, 0)
            elif self.speed < 0:
                self.speed = min(self.speed + self.deceleration, 0)
            
            if self.engine_sound_playing and self.speed == 0:
                engine_sound.stop()
                self.engine_sound_playing = False
        
        # 氮气加速
        if keys[K_SPACE] and self.nitro > 0 and not self.nitro_active:
            self.nitro_active = True
            self.nitro_timer = 180  # 3秒氮气
            self.max_speed = 12
            nitro_sound.play()
        
        if self.nitro_active:
            self.nitro_timer -= 1
            self.nitro = max(0, self.nitro - 0.5)
            if self.nitro_timer <= 0:
                self.nitro_active = False
                self.max_speed = 8
        
        # 转向控制
        self.steering = 0
        if keys[K_LEFT] or keys[K_a]:
            self.steering = -self.max_steering
        if keys[K_RIGHT] or keys[K_d]:
            self.steering = self.max_steering
        
        # 应用转向
        self.x += self.steering * (self.speed / self.max_speed)
        
        # 限制在道路内
        self.x = max(road_left + 20, min(road_right - self.width - 20, self.x))
        
        # 更新位置
        self.y -= self.speed
        
        # 更新漂移角度
        if self.steering != 0 and abs(self.speed) > 2:
            self.drift_angle = self.steering * 0.3
        else:
            self.drift_angle *= 0.9  # 平滑恢复
        
        # 创建刹车痕迹
        if keys[K_DOWN] or keys[K_s] and abs(self.speed) > 1:
            if random.random() < 0.3:  # 30%的几率创建刹车痕
                self.skid_marks.append({
                    'x': self.x + self.width/2 + random.randint(-10, 10),
                    'y': self.y + self.height,
                    'life': 100
                })
        
        # 更新刹车痕迹
        for skid in self.skid_marks[:]:
            skid['life'] -= 2
            if skid['life'] <= 0:
                self.skid_marks.remove(skid)
        
        # 更新碰撞计时器
        if self.crash_timer > 0:
            self.crash_timer -= 1
            self.visible = (self.crash_timer // 5) % 2 == 0  # 闪烁效果
        else:
            self.visible = True
    
    def draw(self, screen):
        """绘制赛车"""
        if not self.visible:
            return
            
        x, y = int(self.x), int(self.y)
        
        # 绘制刹车痕迹
        for skid in self.skid_marks:
            alpha = skid['life'] / 100 * 255
            skid_color = (100, 100, 100, int(alpha))
            skid_surface = pygame.Surface((10, 20), pygame.SRCALPHA)
            skid_surface.fill(skid_color)
            screen.blit(skid_surface, (int(skid['x'] - 5), int(skid['y'] - 10)))
        
        # 创建赛车表面用于旋转
        car_surface = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
        
        # 绘制车身
        pygame.draw.rect(car_surface, self.color, (0, 0, self.width, self.height), border_radius=5)
        
        # 绘制车窗
        pygame.draw.rect(car_surface, (200, 230, 255), 
                        (5, 5, self.width-10, self.height//3), border_radius=3)
        
        # 绘制车灯
        pygame.draw.rect(car_surface, YELLOW, (5, 5, 8, 5), border_radius=2)  # 左前灯
        pygame.draw.rect(car_surface, YELLOW, (self.width-13, 5, 8, 5), border_radius=2)  # 右前灯
        
        # 绘制尾灯
        brake_light = RED if (pygame.key.get_pressed()[K_DOWN] or pygame.key.get_pressed()[K_s]) else (200, 0, 0)
        pygame.draw.rect(car_surface, brake_light, (5, self.height-10, 8, 5), border_radius=2)  # 左尾灯
        pygame.draw.rect(car_surface, brake_light, (self.width-13, self.height-10, 8, 5), border_radius=2)  # 右尾灯
        
        # 绘制车轮
        wheel_color = (20, 20, 20)
        pygame.draw.rect(car_surface, wheel_color, (5, 5, 8, 15), border_radius=2)  # 左前轮
        pygame.draw.rect(car_surface, wheel_color, (self.width-13, 5, 8, 15), border_radius=2)  # 右前轮
        pygame.draw.rect(car_surface, wheel_color, (5, self.height-20, 8, 15), border_radius=2)  # 左后轮
        pygame.draw.rect(car_surface, wheel_color, (self.width-13, self.height-20, 8, 15), border_radius=2)  # 右后轮
        
        # 氮气特效
        if self.nitro_active:
            # 氮气火焰
            flame_height = 20
            flame_points = [
                (self.width//2, self.height),
                (self.width//2 - 10, self.height + flame_height),
                (self.width//2, self.height + flame_height//2),
                (self.width//2 + 10, self.height + flame_height)
            ]
            flame_color = (random.randint(200, 255), random.randint(100, 200), 0)
            pygame.draw.polygon(car_surface, flame_color, flame_points)
        
        # 旋转赛车（漂移效果）
        if abs(self.drift_angle) > 0.01:
            rotated_car = pygame.transform.rotate(car_surface, math.degrees(self.drift_angle))
            rotated_rect = rotated_car.get_rect(center=(x + self.width//2, y + self.height//2))
            screen.blit(rotated_car, rotated_rect)
        else:
            screen.blit(car_surface, (x, y))
        
        # 绘制速度表
        speed_text = font_tiny.render(f"{int(self.speed * 10)} km/h", True, WHITE)
        screen.blit(speed_text, (x, y - 20))
    
    def take_damage(self, amount):
        """受到伤害"""
        if self.crash_timer == 0:  # 只有在不处于无敌状态时才受伤
            self.health -= amount
            self.crash_timer = 60  # 1秒无敌时间
            crash_sound.play()
            return True
        return False
    
    def collect_coin(self, value):
        """收集金币"""
        self.coins += 1
        self.score += value
        collect_sound.play()
    
    def collect_nitro(self, amount):
        """收集氮气"""
        self.nitro = min(self.max_nitro, self.nitro + amount)
        collect_sound.play()
    
    def get_rect(self):
        """获取赛车的碰撞矩形"""
        return pygame.Rect(self.x, self.y, self.width, self.height)

class Road:
    """道路类"""
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.road_y = 0
        self.road_speed = 0
        self.line_width = 10
        self.line_height = 30
        self.line_gap = 20
        self.lines = []
        self.init_lines()
        
    def init_lines(self):
        """初始化道路标线"""
        self.lines = []
        for y in range(-self.line_height, self.height, self.line_height + self.line_gap):
            self.lines.append({
                'x': WIDTH // 2 - self.line_width // 2,
                'y': y
            })
    
    def update(self, car_speed):
        """更新道路"""
        self.road_speed = car_speed
        self.road_y += self.road_speed
        
        # 更新道路标线
        for line in self.lines:
            line['y'] += self.road_speed
            
            # 如果标线移出屏幕，重新放置到顶部
            if line['y'] > self.height:
                line['y'] = -self.line_height
                # 随机偏移x位置，模拟弯曲道路
                line['x'] = WIDTH // 2 - self.line_width // 2 + random.randint(-20, 20)
    
    def draw(self, screen):
        """绘制道路"""
        # 绘制天空
        screen.fill(SKY_BLUE)
        
        # 绘制草地
        road_left = (WIDTH - ROAD_WIDTH) // 2
        road_right = road_left + ROAD_WIDTH
        
        pygame.draw.rect(screen, GRASS_GREEN, (0, 0, road_left - ROAD_MARGIN, HEIGHT))
        pygame.draw.rect(screen, GRASS_GREEN, (road_right + ROAD_MARGIN, 0, WIDTH, HEIGHT))
        
        # 绘制路肩
        shoulder_color = (120, 120, 120)
        pygame.draw.rect(screen, shoulder_color, (road_left - 20, 0, 20, HEIGHT))
        pygame.draw.rect(screen, shoulder_color, (road_right, 0, 20, HEIGHT))
        
        # 绘制道路
        pygame.draw.rect(screen, ROAD_GRAY, (road_left, 0, ROAD_WIDTH, HEIGHT))
        
        # 绘制道路标线
        for line in self.lines:
            pygame.draw.rect(screen, ROAD_LINE, 
                           (line['x'], line['y'], self.line_width, self.line_height))
        
        # 绘制道路边缘线
        edge_color = WHITE
        pygame.draw.rect(screen, edge_color, (road_left, 0, 3, HEIGHT))
        pygame.draw.rect(screen, edge_color, (road_right - 3, 0, 3, HEIGHT))
    
    def get_road_bounds(self):
        """获取道路边界"""
        road_left = (WIDTH - ROAD_WIDTH) // 2
        road_right = road_left + ROAD_WIDTH
        return road_left, road_right

class Obstacle:
    """障碍物类"""
    def __init__(self, x, y, obstacle_type=1):
        self.x = x
        self.y = y
        self.type = obstacle_type
        self.width = OBSTACLE_WIDTH
        self.height = OBSTACLE_HEIGHT
        self.speed = 0
        
        if obstacle_type == 1:  # 锥桶
            self.color = ORANGE
            self.damage = 10
            self.symbol = "△"
        elif obstacle_type == 2:  # 油渍
            self.color = (100, 100, 100, 150)
            self.damage = 5
            self.symbol = "~"
        else:  # 石块
            self.color = DARK_GRAY
            self.damage = 15
            self.symbol = "◈"
        
    def update(self, speed):
        """更新障碍物位置"""
        self.y += speed
        self.speed = speed
    
    def draw(self, screen):
        """绘制障碍物"""
        if self.type == 2:  # 油渍是半透明的
            oil_surface = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
            pygame.draw.ellipse(oil_surface, self.color, (0, 0, self.width, self.height))
            screen.blit(oil_surface, (self.x, self.y))
            
            # 绘制油渍符号
            oil_text = font_tiny.render(self.symbol, True, BLACK)
            text_rect = oil_text.get_rect(center=(self.x + self.width//2, self.y + self.height//2))
            screen.blit(oil_text, text_rect)
        else:
            pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height), border_radius=5)
            
            # 绘制障碍物符号
            obs_text = font_tiny.render(self.symbol, True, WHITE)
            text_rect = obs_text.get_rect(center=(self.x + self.width//2, self.y + self.height//2))
            screen.blit(obs_text, text_rect)
            
            # 添加边框
            pygame.draw.rect(screen, BLACK, (self.x, self.y, self.width, self.height), 2, border_radius=5)
    
    def is_off_screen(self):
        """检查是否离开屏幕"""
        return self.y > HEIGHT
    
    def get_rect(self):
        """获取障碍物的碰撞矩形"""
        return pygame.Rect(self.x, self.y, self.width, self.height)

class Coin:
    """金币类"""
    def __init__(self, x, y, value=10):
        self.x = x
        self.y = y
        self.value = value
        self.radius = COIN_RADIUS
        self.collected = False
        self.rotation = 0
        self.float_offset = 0
        self.float_direction = 1
        
    def update(self, speed):
        """更新金币位置"""
        self.y += speed
        self.rotation = (self.rotation + 5) % 360
        
        # 上下浮动效果
        self.float_offset += 0.1 * self.float_direction
        if abs(self.float_offset) > 3:
            self.float_direction *= -1
    
    def draw(self, screen):
        """绘制金币"""
        if self.collected:
            return
            
        x, y = int(self.x), int(self.y + self.float_offset)
        
        # 绘制金币
        pygame.draw.circle(screen, YELLOW, (x, y), self.radius)
        pygame.draw.circle(screen, (200, 180, 0), (x, y), self.radius, 3)
        
        # 绘制金币符号
        coin_text = font_small.render("$", True, BLACK)
        text_rect = coin_text.get_rect(center=(x, y))
        screen.blit(coin_text, text_rect)
        
        # 绘制光芒
        for i in range(8):
            angle = math.radians(self.rotation + i * 45)
            px1 = x + math.cos(angle) * (self.radius - 2)
            py1 = y + math.sin(angle) * (self.radius - 2)
            px2 = x + math.cos(angle) * (self.radius + 5)
            py2 = y + math.sin(angle) * (self.radius + 5)
            
            if i % 2 == 0:
                pygame.draw.line(screen, YELLOW, (int(px1), int(py1)), (int(px2), int(py2)), 2)
    
    def is_off_screen(self):
        """检查是否离开屏幕"""
        return self.y > HEIGHT
    
    def get_rect(self):
        """获取金币的碰撞矩形"""
        return pygame.Rect(self.x - self.radius, self.y - self.radius, 
                          self.radius * 2, self.radius * 2)

class NitroPickup:
    """氮气道具类"""
    def __init__(self, x, y, amount=25):
        self.x = x
        self.y = y
        self.amount = amount
        self.radius = NITRO_RADIUS
        self.collected = False
        self.rotation = 0
        self.pulse = 0
        self.pulse_direction = 1
        
    def update(self, speed):
        """更新氮气位置"""
        self.y += speed
        self.rotation = (self.rotation + 3) % 360
        
        # 脉动效果
        self.pulse += 0.2 * self.pulse_direction
        if abs(self.pulse) > 5:
            self.pulse_direction *= -1
    
    def draw(self, screen):
        """绘制氮气"""
        if self.collected:
            return
            
        x, y = int(self.x), int(self.y)
        current_radius = int(self.radius + self.pulse)
        
        # 绘制氮气罐
        pygame.draw.circle(screen, CYAN, (x, y), current_radius)
        pygame.draw.circle(screen, (0, 200, 200), (x, y), current_radius, 3)
        
        # 绘制氮气符号
        nitro_text = font_small.render("N₂", True, BLACK)
        text_rect = nitro_text.get_rect(center=(x, y))
        screen.blit(nitro_text, text_rect)
        
        # 绘制旋转效果
        for i in range(4):
            angle = math.radians(self.rotation + i * 90)
            px = x + math.cos(angle) * (current_radius + 5)
            py = y + math.sin(angle) * (current_radius + 5)
            pygame.draw.circle(screen, WHITE, (int(px), int(py)), 3)
    
    def is_off_screen(self):
        """检查是否离开屏幕"""
        return self.y > HEIGHT
    
    def get_rect(self):
        """获取氮气的碰撞矩形"""
        return pygame.Rect(self.x - self.radius, self.y - self.radius, 
                          self.radius * 2, self.radius * 2)

class Game:
    """游戏主类"""
    def __init__(self):
        self.road = None
        self.car = None
        self.obstacles = []
        self.coins = []
        self.nitro_pickups = []
        self.level = 1
        self.score = 0
        self.distance = 0
        self.game_state = "start"  # start, playing, paused, level_complete, game_over, victory
        self.start_time = pygame.time.get_ticks()
        self.obstacle_timer = 0
        self.coin_timer = 0
        self.nitro_timer = 0
        self.level_distance = 1000
        self.background_items = []
        
        self.init_game()
    
    def init_game(self):
        """初始化游戏"""
        self.road = Road(WIDTH, HEIGHT)
        road_left, road_right = self.road.get_road_bounds()
        car_x = (road_left + road_right) // 2 - CAR_WIDTH // 2
        car_y = HEIGHT - 150
        
        self.car = Car(car_x, car_y)
        self.obstacles = []
        self.coins = []
        self.nitro_pickups = []
        self.obstacle_timer = 0
        self.coin_timer = 0
        self.nitro_timer = 0
        self.distance = 0
        
        # 初始化背景物体（树木、建筑等）
        self.init_background()
    
    def init_background(self):
        """初始化背景物体"""
        self.background_items = []
        road_left, road_right = self.road.get_road_bounds()
        
        # 在道路两侧添加树木
        for _ in range(20):
            side = random.choice(["left", "right"])
            if side == "left":
                x = random.randint(20, road_left - ROAD_MARGIN - 30)
            else:
                x = random.randint(road_right + ROAD_MARGIN + 20, WIDTH - 50)
            
            y = random.randint(-HEIGHT, HEIGHT)
            size = random.randint(20, 40)
            color = random.choice([DARK_GREEN, (0, 120, 0), (30, 100, 30)])
            
            self.background_items.append({
                'type': 'tree',
                'x': x,
                'y': y,
                'size': size,
                'color': color,
                'speed': 0
            })
        
        # 添加建筑
        for _ in range(10):
            side = random.choice(["left", "right"])
            if side == "left":
                x = random.randint(20, road_left - ROAD_MARGIN - 100)
            else:
                x = random.randint(road_right + ROAD_MARGIN + 20, WIDTH - 120)
            
            y = random.randint(-HEIGHT, HEIGHT)
            width = random.randint(60, 120)
            height = random.randint(80, 200)
            color = random.choice([GRAY, (120, 120, 120), (80, 80, 80)])
            
            self.background_items.append({
                'type': 'building',
                'x': x,
                'y': y,
                'width': width,
                'height': height,
                'color': color,
                'speed': 0
            })
    
    def update_background(self, speed):
        """更新背景物体"""
        for item in self.background_items:
            item['y'] += speed
            item['speed'] = speed
            
            # 如果物体移出屏幕，重新放置到顶部
            if item['y'] > HEIGHT + 200:
                item['y'] = -200
                road_left, road_right = self.road.get_road_bounds()
                
                if item['type'] == 'tree':
                    side = random.choice(["left", "right"])
                    if side == "left":
                        item['x'] = random.randint(20, road_left - ROAD_MARGIN - 30)
                    else:
                        item['x'] = random.randint(road_right + ROAD_MARGIN + 20, WIDTH - 50)
                else:  # building
                    side = random.choice(["left", "right"])
                    if side == "left":
                        item['x'] = random.randint(20, road_left - ROAD_MARGIN - 100)
                    else:
                        item['x'] = random.randint(road_right + ROAD_MARGIN + 20, WIDTH - 120)
    
    def draw_background(self, screen):
        """绘制背景物体"""
        for item in self.background_items:
            if item['type'] == 'tree':
                x, y = int(item['x']), int(item['y'])
                size = item['size']
                
                # 绘制树干
                trunk_width = size // 4
                trunk_height = size
                pygame.draw.rect(screen, (101, 67, 33), 
                               (x - trunk_width//2, y, trunk_width, trunk_height))
                
                # 绘制树冠
                pygame.draw.circle(screen, item['color'], (x, y - size//3), size//2)
                
                # 添加树木阴影（基于速度）
                if item['speed'] > 0:
                    shadow_offset = min(10, item['speed'] * 0.5)
                    pygame.draw.circle(screen, (0, 0, 0, 100), 
                                     (x + shadow_offset, y - size//3), size//2)
            
            elif item['type'] == 'building':
                x, y = int(item['x']), int(item['y'])
                width, height = item['width'], item['height']
                
                # 绘制建筑主体
                pygame.draw.rect(screen, item['color'], (x, y, width, height))
                
                # 绘制窗户
                window_size = 15
                window_margin = 10
                window_color = random.choice([YELLOW, (200, 200, 150), WHITE])
                
                for wx in range(x + window_margin, x + width - window_margin, window_size + window_margin):
                    for wy in range(y + window_margin, y + height - window_margin, window_size + window_margin):
                        if random.random() < 0.7:  # 70%的窗户亮着
                            pygame.draw.rect(screen, window_color, 
                                           (wx, wy, window_size, window_size))
                
                # 添加建筑阴影
                if item['speed'] > 0:
                    shadow_offset = min(15, item['speed'] * 0.8)
                    shadow_surface = pygame.Surface((width, height), pygame.SRCALPHA)
                    shadow_surface.fill((0, 0, 0, 100))
                    screen.blit(shadow_surface, (x + shadow_offset, y))
    
    def update(self):
        """更新游戏状态"""
        if self.game_state != "playing":
            return
        
        # 更新距离
        self.distance += abs(self.car.speed)
        
        # 更新道路
        self.road.update(self.car.speed)
        
        # 更新背景
        self.update_background(self.car.speed * 0.5)
        
        # 生成障碍物
        self.obstacle_timer += 1
        if self.obstacle_timer >= max(30, 60 - self.level * 5):
            self.obstacle_timer = 0
            road_left, road_right = self.road.get_road_bounds()
            
            x = random.randint(road_left + 30, road_right - OBSTACLE_WIDTH - 30)
            y = -OBSTACLE_HEIGHT
            obstacle_type = random.choice([1, 2, 3])
            
            self.obstacles.append(Obstacle(x, y, obstacle_type))
        
        # 生成金币
        self.coin_timer += 1
        if self.coin_timer >= 45:
            self.coin_timer = 0
            road_left, road_right = self.road.get_road_bounds()
            
            x = random.randint(road_left + 30, road_right - 30)
            y = -COIN_RADIUS * 2
            value = random.choice([10, 20, 50])
            
            self.coins.append(Coin(x, y, value))
        
        # 生成氮气
        self.nitro_timer += 1
        if self.nitro_timer >= 300:  # 每5秒生成一个
            self.nitro_timer = 0
            road_left, road_right = self.road.get_road_bounds()
            
            x = random.randint(road_left + 30, road_right - 30)
            y = -NITRO_RADIUS * 2
            amount = random.choice([25, 50])
            
            self.nitro_pickups.append(NitroPickup(x, y, amount))
        
        # 更新障碍物
        for obstacle in self.obstacles[:]:
            obstacle.update(self.car.speed)
            
            # 检查碰撞
            if self.car.get_rect().colliderect(obstacle.get_rect()):
                if self.car.take_damage(obstacle.damage):
                    if self.car.health <= 0:
                        self.game_state = "game_over"
                        game_over_sound.play()
                        engine_sound.stop()
                        self.car.engine_sound_playing = False
            
            if obstacle.is_off_screen():
                self.obstacles.remove(obstacle)
        
        # 更新金币
        for coin in self.coins[:]:
            coin.update(self.car.speed)
            
            # 检查收集
            if self.car.get_rect().colliderect(coin.get_rect()):
                self.car.collect_coin(coin.value)
                self.score += coin.value
                coin.collected = True
            
            if coin.is_off_screen() or coin.collected:
                if coin in self.coins:
                    self.coins.remove(coin)
        
        # 更新氮气
        for nitro in self.nitro_pickups[:]:
            nitro.update(self.car.speed)
            
            # 检查收集
            if self.car.get_rect().colliderect(nitro.get_rect()):
                self.car.collect_nitro(nitro.amount)
                nitro.collected = True
            
            if nitro.is_off_screen() or nitro.collected:
                if nitro in self.nitro_pickups:
                    self.nitro_pickups.remove(nitro)
        
        # 检查是否完成关卡
        if self.distance >= self.level_distance:
            if self.level >= 5:
                self.game_state = "victory"
                victory_sound.play()
                engine_sound.stop()
                self.car.engine_sound_playing = False
            else:
                self.game_state = "level_complete"
                victory_sound.play()
                engine_sound.stop()
                self.car.engine_sound_playing = False
    
    def draw(self, screen):
        """绘制游戏"""
        # 绘制背景
        self.road.draw(screen)
        
        # 绘制背景物体
        self.draw_background(screen)
        
        # 绘制氮气道具
        for nitro in self.nitro_pickups:
            nitro.draw(screen)
        
        # 绘制金币
        for coin in self.coins:
            coin.draw(screen)
        
        # 绘制障碍物
        for obstacle in self.obstacles:
            obstacle.draw(screen)
        
        # 绘制赛车
        self.car.draw(screen)
        
        # 绘制HUD
        self.draw_hud(screen)
        
        # 绘制游戏状态界面
        if self.game_state == "start":
            self.draw_start_screen(screen)
        elif self.game_state == "paused":
            self.draw_pause_screen(screen)
        elif self.game_state == "level_complete":
            self.draw_level_complete_screen(screen)
        elif self.game_state == "game_over":
            self.draw_game_over_screen(screen)
        elif self.game_state == "victory":
            self.draw_victory_screen(screen)
    
    def draw_hud(self, screen):
        """绘制游戏信息界面"""
        # 绘制分数
        score_text = font_small.render(f"分数: {self.score}", True, WHITE)
        screen.blit(score_text, (20, 20))
        
        # 绘制金币
        coins_text = font_small.render(f"金币: {self.car.coins}", True, YELLOW)
        screen.blit(coins_text, (20, 50))
        
        # 绘制距离
        distance_text = font_small.render(f"距离: {int(self.distance)}/{self.level_distance}m", True, WHITE)
        screen.blit(distance_text, (20, 80))
        
        # 绘制等级
        level_text = font_small.render(f"等级: {self.level}", True, WHITE)
        screen.blit(level_text, (20, 110))
        
        # 绘制血量条
        health_text = font_small.render("血量:", True, WHITE)
        screen.blit(health_text, (WIDTH - 200, 20))
        
        health_bar_width = 180
        health_bar_height = 20
        health_percent = self.car.health / 100
        
        pygame.draw.rect(screen, DARK_GRAY, (WIDTH - 180, 20, health_bar_width, health_bar_height))
        pygame.draw.rect(screen, 
                        GREEN if health_percent > 0.5 else YELLOW if health_percent > 0.2 else RED,
                        (WIDTH - 178, 22, int((health_bar_width - 4) * health_percent), health_bar_height - 4))
        
        health_value = font_tiny.render(f"{int(self.car.health)}%", True, WHITE)
        screen.blit(health_value, (WIDTH - 90, 25))
        
        # 绘制氮气条
        nitro_text = font_small.render("氮气:", True, WHITE)
        screen.blit(nitro_text, (WIDTH - 200, 50))
        
        nitro_bar_width = 180
        nitro_bar_height = 20
        nitro_percent = self.car.nitro / self.car.max_nitro
        
        pygame.draw.rect(screen, DARK_GRAY, (WIDTH - 180, 50, nitro_bar_width, nitro_bar_height))
        pygame.draw.rect(screen, CYAN, 
                        (WIDTH - 178, 52, int((nitro_bar_width - 4) * nitro_percent), nitro_bar_height - 4))
        
        if self.car.nitro_active:
            nitro_status = font_tiny.render("氮气加速中!", True, CYAN)
            screen.blit(nitro_status, (WIDTH - 180, 80))
        
        nitro_value = font_tiny.render(f"{int(self.car.nitro)}%", True, WHITE)
        screen.blit(nitro_value, (WIDTH - 90, 55))
        
        # 绘制速度表
        speed = abs(self.car.speed) * 10
        speed_text = font_medium.render(f"{int(speed)} km/h", True, 
                                       GREEN if speed < 30 else YELLOW if speed < 60 else RED)
        screen.blit(speed_text, (WIDTH // 2 - 50, 20))
        
        # 绘制控制提示
        controls = [
            "控制: ↑加速 ↓刹车 ←→转向",
            "空格: 氮气加速",
            "P: 暂停游戏",
            "ESC: 返回主菜单"
        ]
        
        for i, control in enumerate(controls):
            control_text = font_tiny.render(control, True, LIGHT_GRAY)
            screen.blit(control_text, (WIDTH - 250, HEIGHT - 100 + i * 25))
    
    def draw_start_screen(self, screen):
        """绘制开始画面"""
        overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 200))
        screen.blit(overlay, (0, 0))
        
        # 标题
        title_text = font_large.render("极速狂飙", True, RED)
        screen.blit(title_text, (WIDTH // 2 - 100, HEIGHT // 2 - 150))
        
        subtitle_text = font_medium.render("赛车挑战", True, YELLOW)
        screen.blit(subtitle_text, (WIDTH // 2 - 80, HEIGHT // 2 - 100))
        
        # 绘制示例赛车
        car_example = Car(WIDTH // 2 - CAR_WIDTH // 2, HEIGHT // 2 - 50)
        car_example.draw(screen)
        
        # 游戏说明
        instructions = [
            "游戏目标: 完成每个等级的赛道，避开障碍物，收集金币",
            "",
            "控制说明:",
            "↑/W: 加速前进",
            "↓/S: 刹车/倒车",
            "←/A: 向左转向",
            "→/D: 向右转向",
            "空格键: 氮气加速（需要收集氮气）",
            "",
            "游戏元素:",
            "💰 金币: 收集获得分数",
            "🔵 氮气: 收集后按空格键加速",
            "⚠️ 橙色锥桶: 碰撞减少10点血量",
            "💧 黑色油渍: 碰撞减少5点血量，会打滑",
            "🪨 灰色石块: 碰撞减少15点血量",
            "",
            "等级系统:",
            "1. 完成1000米到达下一等级",
            "2. 每个等级障碍物更多",
            "3. 完成5个等级获得胜利",
            "",
            "提示: 注意控制速度，合理使用氮气加速!"
        ]
        
        for i, instruction in enumerate(instructions):
            color = YELLOW if i == 0 else WHITE
            instruction_text = font_tiny.render(instruction, True, color)
            screen.blit(instruction_text, (WIDTH // 2 - 300, HEIGHT // 2 - 30 + i * 20))
        
        # 开始游戏提示
        start_text = font_medium.render("按空格键开始游戏", True, GREEN)
        screen.blit(start_text, (WIDTH // 2 - 100, HEIGHT - 100))
    
    def draw_pause_screen(self, screen):
        """绘制暂停画面"""
        overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 150))
        screen.blit(overlay, (0, 0))
        
        pause_text = font_large.render("游戏暂停", True, YELLOW)
        screen.blit(pause_text, (WIDTH // 2 - 100, HEIGHT // 2 - 50))
        
        continue_text = font_medium.render("按P键继续游戏", True, WHITE)
        screen.blit(continue_text, (WIDTH // 2 - 100, HEIGHT // 2 + 20))
        
        menu_text = font_medium.render("按ESC键返回主菜单", True, WHITE)
        screen.blit(menu_text, (WIDTH // 2 - 120, HEIGHT // 2 + 60))
    
    def draw_level_complete_screen(self, screen):
        """绘制关卡完成画面"""
        overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 200))
        screen.blit(overlay, (0, 0))
        
        # 关卡完成文字
        level_text = font_large.render(f"第 {self.level} 关完成!", True, GREEN)
        screen.blit(level_text, (WIDTH // 2 - 120, HEIGHT // 2 - 100))
        
        # 统计信息
        time_bonus = int(self.distance * 0.5)
        health_bonus = int(self.car.health * 2)
        total_bonus = time_bonus + health_bonus
        
        stats = [
            f"收集金币: {self.car.coins} 枚",
            f"剩余血量: {self.car.health}% (+{health_bonus}分)",
            f"行驶距离: {int(self.distance)}米 (+{time_bonus}分)",
            f"当前分数: {self.score}",
            f"奖励分数: +{total_bonus}分"
        ]
        
        for i, stat in enumerate(stats):
            stat_text = font_medium.render(stat, True, WHITE)
            screen.blit(stat_text, (WIDTH // 2 - 150, HEIGHT // 2 - 50 + i * 40))
        
        # 下一关提示
        if self.level < 5:
            next_text = font_medium.render("按空格键进入下一关", True, YELLOW)
            screen.blit(next_text, (WIDTH // 2 - 120, HEIGHT // 2 + 150))
        else:
            next_text = font_medium.render("按空格键查看最终胜利", True, YELLOW)
            screen.blit(next_text, (WIDTH // 2 - 120, HEIGHT // 2 + 150))
        
        # 返回菜单提示
        menu_text = font_small.render("按ESC键返回主菜单", True, LIGHT_GRAY)
        screen.blit(menu_text, (WIDTH // 2 - 100, HEIGHT // 2 + 200))
    
    def draw_game_over_screen(self, screen):
        """绘制游戏结束画面"""
        overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 200))
        screen.blit(overlay, (0, 0))
        
        # 游戏结束文字
        game_over_text = font_large.render("游戏结束!", True, RED)
        screen.blit(game_over_text, (WIDTH // 2 - 100, HEIGHT // 2 - 100))
        
        # 统计信息
        stats = [
            f"到达等级: {self.level}",
            f"最终分数: {self.score}",
            f"收集金币: {self.car.coins}",
            f"行驶距离: {int(self.distance)}米"
        ]
        
        for i, stat in enumerate(stats):
            stat_text = font_medium.render(stat, True, WHITE)
            screen.blit(stat_text, (WIDTH // 2 - 100, HEIGHT // 2 - 50 + i * 40))
        
        # 重新开始提示
        restart_text = font_medium.render("按R键重新开始本关", True, GREEN)
        screen.blit(restart_text, (WIDTH // 2 - 100, HEIGHT // 2 + 120))
        
        menu_text = font_medium.render("按ESC键返回主菜单", True, YELLOW)
        screen.blit(menu_text, (WIDTH // 2 - 100, HEIGHT // 2 + 170))
    
    def draw_victory_screen(self, screen):
        """绘制胜利画面"""
        overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 200))
        screen.blit(overlay, (0, 0))
        
        # 胜利文字
        victory_text = font_large.render("恭喜通关!", True, YELLOW)
        screen.blit(victory_text, (WIDTH // 2 - 100, HEIGHT // 2 - 150))
        
        complete_text = font_medium.render("你成功完成了所有赛车挑战!", True, GREEN)
        screen.blit(complete_text, (WIDTH // 2 - 150, HEIGHT // 2 - 100))
        
        # 最终统计
        time_bonus = int(self.distance * 0.5)
        health_bonus = int(self.car.health * 2)
        total_bonus = time_bonus + health_bonus
        
        stats = [
            f"最终分数: {self.score + total_bonus}",
            f"总收集金币: {self.car.coins}",
            f"总行驶距离: {int(self.distance)}米",
            f"通关等级: 5/5",
            f"奖励分数: +{total_bonus}分"
        ]
        
        for i, stat in enumerate(stats):
            stat_text = font_medium.render(stat, True, WHITE)
            screen.blit(stat_text, (WIDTH // 2 - 100, HEIGHT // 2 - 50 + i * 40))
        
        # 重新开始提示
        restart_text = font_medium.render("按R键重新开始游戏", True, GREEN)
        screen.blit(restart_text, (WIDTH // 2 - 100, HEIGHT // 2 + 150))
        
        menu_text = font_medium.render("按ESC键返回主菜单", True, YELLOW)
        screen.blit(menu_text, (WIDTH // 2 - 100, HEIGHT // 2 + 200))
    
    def next_level(self):
        """进入下一关"""
        # 添加奖励分数
        time_bonus = int(self.distance * 0.5)
        health_bonus = int(self.car.health * 2)
        self.score += time_bonus + health_bonus
        
        self.level += 1
        self.level_distance = 1000 + (self.level - 1) * 200
        self.init_game()
        self.game_state = "playing"
    
    def restart_level(self):
        """重新开始当前关卡"""
        self.init_game()
        self.game_state = "playing"
    
    def restart_game(self):
        """重新开始游戏"""
        self.level = 1
        self.score = 0
        self.level_distance = 1000
        self.init_game()
        self.game_state = "playing"

def main():
    """主游戏函数"""
    clock = pygame.time.Clock()
    game = Game()
    
    # 主游戏循环
    running = True
    while running:
        clock.tick(FPS)
        
        # 处理事件
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    if game.game_state in ["playing", "paused", "level_complete", "game_over", "victory"]:
                        game.game_state = "start"
                    else:
                        running = False
                elif event.key == K_SPACE:
                    if game.game_state == "start":
                        game.game_state = "playing"
                    elif game.game_state == "level_complete":
                        game.next_level()
                    elif game.game_state == "victory":
                        game.restart_game()
                elif event.key == K_p:
                    if game.game_state == "playing":
                        game.game_state = "paused"
                    elif game.game_state == "paused":
                        game.game_state = "playing"
                elif event.key == K_r:
                    if game.game_state in ["playing", "game_over", "victory"]:
                        game.restart_level()
        
        # 获取按键状态
        keys = pygame.key.get_pressed()
        
        # 处理玩家输入
        if game.game_state == "playing":
            road_left, road_right = game.road.get_road_bounds()
            game.car.update(keys, road_left, road_right)
        
        # 更新游戏状态
        if game.game_state == "playing":
            game.update()
        
        # 绘制游戏
        game.draw(screen)
        
        pygame.display.flip()
    
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()