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

# 初始化 Pygame
pygame.init()

# 游戏窗口设置
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("2D赛车挑战赛")

# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 50, 50)
GREEN = (50, 255, 50)
BLUE = (50, 100, 255)
YELLOW = (255, 255, 50)
ORANGE = (255, 165, 0)
GRAY = (100, 100, 100)
LIGHT_GRAY = (200, 200, 200)
DARK_GRAY = (50, 50, 50)
GRASS_GREEN = (60, 180, 75)
ROAD_GRAY = (100, 100, 100)
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)]))
except:
    class SilentSound:
        def play(self): pass
    engine_sound = SilentSound()
    crash_sound = SilentSound()
    collect_sound = SilentSound()
    victory_sound = SilentSound()
    game_over_sound = SilentSound()

# 游戏参数
CAR_WIDTH = 40
CAR_HEIGHT = 60
ROAD_WIDTH = 300
ROAD_SPEED = 5
OBSTACLE_WIDTH = 40
OBSTACLE_HEIGHT = 40
COIN_SIZE = 20
FPS = 60

class Car:
    """赛车类"""
    def __init__(self):
        self.x = WIDTH // 2 - CAR_WIDTH // 2
        self.y = HEIGHT - 150
        self.width = CAR_WIDTH
        self.height = CAR_HEIGHT
        self.speed = 0
        self.max_speed = 8
        self.acceleration = 0.2
        self.deceleration = 0.1
        self.color = RED
        self.health = 100
        self.score = 0
        self.coins = 0
        self.visible = True
        self.crash_timer = 0
        self.engine_sound_playing = False
        
    def update(self, keys):
        """更新赛车状态"""
        # 左右移动
        if keys[K_LEFT] or keys[K_a]:
            self.x -= 5
        if keys[K_RIGHT] or keys[K_d]:
            self.x += 5
        
        # 加速/减速
        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 - 0.3, 0)
        else:
            if self.speed > 0:
                self.speed = max(self.speed - self.deceleration, 0)
            
            if self.engine_sound_playing and self.speed == 0:
                engine_sound.stop()
                self.engine_sound_playing = False
        
        # 限制在屏幕内
        self.x = max(0, min(WIDTH - self.width, self.x))
        
        # 更新碰撞计时器
        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)
        
        # 绘制车身
        pygame.draw.rect(screen, self.color, (x, y, self.width, self.height), border_radius=5)
        
        # 绘制车窗
        pygame.draw.rect(screen, (200, 230, 255), 
                        (x + 5, y + 5, self.width - 10, self.height // 3), border_radius=3)
        
        # 绘制车灯
        pygame.draw.rect(screen, YELLOW, (x + 5, y + 5, 8, 5), border_radius=2)
        pygame.draw.rect(screen, YELLOW, (x + self.width - 13, y + 5, 8, 5), border_radius=2)
        
        # 绘制车轮
        wheel_color = (20, 20, 20)
        pygame.draw.rect(screen, wheel_color, (x + 5, y + 5, 8, 15), border_radius=2)
        pygame.draw.rect(screen, wheel_color, (x + self.width - 13, y + 5, 8, 15), border_radius=2)
        pygame.draw.rect(screen, wheel_color, (x + 5, y + self.height - 20, 8, 15), border_radius=2)
        pygame.draw.rect(screen, wheel_color, (x + self.width - 13, y + self.height - 20, 8, 15), border_radius=2)
        
        # 绘制速度指示
        if self.speed > 0:
            speed_text = font_tiny.render(f"{int(self.speed * 10)}", 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
            crash_sound.play()
            return True
        return False
    
    def collect_coin(self, value):
        """收集金币"""
        self.coins += 1
        self.score += value
        collect_sound.play()
    
    def get_rect(self):
        """获取赛车的碰撞矩形"""
        return pygame.Rect(self.x, self.y, self.width, self.height)

class Road:
    """道路类"""
    def __init__(self):
        self.road_y = 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, HEIGHT, self.line_height + self.line_gap):
            self.lines.append({
                'x': WIDTH // 2 - self.line_width // 2,
                'y': y
            })
    
    def update(self, speed):
        """更新道路"""
        self.road_y += speed
        
        for line in self.lines:
            line['y'] += speed
            
            if line['y'] > HEIGHT:
                line['y'] = -self.line_height
                line['x'] = WIDTH // 2 - self.line_width // 2
    
    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, HEIGHT))
        pygame.draw.rect(screen, GRASS_GREEN, (road_right, 0, WIDTH, 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))
        
        # 绘制道路边缘
        pygame.draw.rect(screen, WHITE, (road_left, 0, 3, HEIGHT))
        pygame.draw.rect(screen, WHITE, (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, obstacle_type=1):
        self.type = obstacle_type
        self.width = OBSTACLE_WIDTH
        self.height = OBSTACLE_HEIGHT
        road_left, road_right = ROAD_WIDTH, WIDTH - ROAD_WIDTH
        road_center = (road_left + road_right) // 2
        road_range = ROAD_WIDTH - self.width - 20
        
        self.x = road_center - road_range // 2 + random.randint(0, road_range)
        self.y = -self.height
        
        if obstacle_type == 1:  # 锥桶
            self.color = ORANGE
            self.damage = 10
        elif obstacle_type == 2:  # 油渍
            self.color = DARK_GRAY
            self.damage = 5
        else:  # 石块
            self.color = GRAY
            self.damage = 15
        
    def update(self, speed):
        """更新障碍物位置"""
        self.y += speed
    
    def draw(self, screen):
        """绘制障碍物"""
        pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height), border_radius=5)
        pygame.draw.rect(screen, BLACK, (self.x, self.y, self.width, self.height), 2, border_radius=5)
        
        # 根据类型绘制符号
        if self.type == 1:
            symbol = "△"
        elif self.type == 2:
            symbol = "~"
        else:
            symbol = "◈"
        
        symbol_font = pygame.font.Font(None, 20)
        symbol_text = symbol_font.render(symbol, True, WHITE)
        text_rect = symbol_text.get_rect(center=(self.x + self.width//2, self.y + self.height//2))
        screen.blit(symbol_text, text_rect)
    
    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):
        self.size = COIN_SIZE
        road_left, road_right = ROAD_WIDTH, WIDTH - ROAD_WIDTH
        road_center = (road_left + road_right) // 2
        road_range = ROAD_WIDTH - self.size - 20
        
        self.x = road_center - road_range // 2 + random.randint(0, road_range)
        self.y = -self.size
        self.value = random.choice([10, 20, 50])
        self.collected = False
        self.rotation = 0
        
    def update(self, speed):
        """更新金币位置"""
        self.y += speed
        self.rotation = (self.rotation + 5) % 360
    
    def draw(self, screen):
        """绘制金币"""
        if self.collected:
            return
            
        x, y = int(self.x), int(self.y)
        
        # 绘制金币
        pygame.draw.circle(screen, YELLOW, (x, y), self.size//2)
        pygame.draw.circle(screen, (200, 180, 0), (x, y), self.size//2, 3)
        
        # 绘制金币符号
        coin_text = font_small.render("$", True, BLACK)
        text_rect = coin_text.get_rect(center=(x, y))
        screen.blit(coin_text, text_rect)
    
    def is_off_screen(self):
        """检查是否离开屏幕"""
        return self.y > HEIGHT
    
    def get_rect(self):
        """获取金币的碰撞矩形"""
        return pygame.Rect(self.x - self.size//2, self.y - self.size//2, 
                          self.size, self.size)

class Game:
    """游戏主类"""
    def __init__(self):
        self.road = None
        self.car = None
        self.obstacles = []
        self.coins = []
        self.level = 1
        self.score = 0
        self.distance = 0
        self.game_state = "start"
        self.obstacle_timer = 0
        self.coin_timer = 0
        self.level_distance = 1000
        
        self.init_game()
    
    def init_game(self):
        """初始化游戏"""
        self.road = Road()
        self.car = Car()
        self.obstacles = []
        self.coins = []
        self.obstacle_timer = 0
        self.coin_timer = 0
        self.distance = 0
    
    def update(self):
        """更新游戏状态"""
        if self.game_state != "playing":
            return
        
        # 更新距离
        self.distance += self.car.speed
        
        # 更新道路
        self.road.update(self.car.speed)
        
        # 生成障碍物
        self.obstacle_timer += 1
        if self.obstacle_timer >= max(30, 60 - self.level * 5):
            self.obstacle_timer = 0
            obstacle_type = random.choice([1, 2, 3])
            self.obstacles.append(Obstacle(obstacle_type))
        
        # 生成金币
        self.coin_timer += 1
        if self.coin_timer >= 45:
            self.coin_timer = 0
            self.coins.append(Coin())
        
        # 更新障碍物
        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)
        
        # 检查是否完成关卡
        if self.distance >= self.level_distance:
            if self.level >= 3:
                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)
        
        # 绘制金币
        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 == "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(f"血量: {self.car.health}", True, 
                                       GREEN if self.car.health > 50 else YELLOW if self.car.health > 20 else RED)
        screen.blit(health_text, (WIDTH - 150, 20))
        
        # 绘制血量条
        health_bar_width = 120
        health_bar_height = 20
        health_percent = self.car.health / 100
        
        pygame.draw.rect(screen, DARK_GRAY, (WIDTH - 130, 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 - 128, 22, int((health_bar_width - 4) * health_percent), health_bar_height - 4))
        
        # 绘制控制提示
        controls = [
            "控制: ←→移动 ↑加速 ↓刹车",
            "P: 暂停 ESC: 菜单"
        ]
        
        for i, control in enumerate(controls):
            control_text = font_tiny.render(control, True, LIGHT_GRAY)
            screen.blit(control_text, (WIDTH - 180, HEIGHT - 50 + 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("2D赛车挑战赛", True, RED)
        screen.blit(title_text, (WIDTH // 2 - 120, HEIGHT // 2 - 100))
        
        # 绘制示例赛车
        car_example = Car()
        car_example.draw(screen)
        
        # 游戏说明
        instructions = [
            "游戏目标: 完成每个等级的赛道，避开障碍物，收集金币",
            "",
            "控制说明:",
            "←/A: 向左移动",
            "→/D: 向右移动",
            "↑/W: 加速前进",
            "↓/S: 刹车减速",
            "",
            "游戏元素:",
            "$ 金币: 收集获得10/20/50分",
            "△ 锥桶: 碰撞减少10点血量",
            "~ 油渍: 碰撞减少5点血量",
            "◈ 石块: 碰撞减少15点血量",
            "",
            "提示: 控制好速度，避开障碍物!"
        ]
        
        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 - 200, HEIGHT // 2 - 30 + i * 20))
        
        # 开始游戏提示
        start_text = font_medium.render("按空格键开始游戏", True, GREEN)
        screen.blit(start_text, (WIDTH // 2 - 100, HEIGHT - 100))
    
    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 - 100, HEIGHT // 2 - 100))
        
        # 统计信息
        time_bonus = int(self.distance * 0.5)
        health_bonus = int(self.car.health * 2)
        
        stats = [
            f"收集金币: {self.car.coins} 枚",
            f"剩余血量: {self.car.health}%",
            f"行驶距离: {int(self.distance)}米",
            f"当前分数: {self.score}",
            f"奖励分数: +{time_bonus + health_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 < 3:
            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"通关等级: 3/3"
        ]
        
        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", "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":
                        # 简单暂停
                        paused = True
                        while paused:
                            for event in pygame.event.get():
                                if event.type == QUIT:
                                    pygame.quit()
                                    sys.exit()
                                elif event.type == KEYDOWN:
                                    if event.key == K_p:
                                        paused = False
                                    elif event.key == K_ESCAPE:
                                        game.game_state = "start"
                                        paused = False
                            
                            # 绘制暂停画面
                            screen.fill((0, 0, 0, 150))
                            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 - 80, HEIGHT//2 + 20))
                            pygame.display.flip()
                            clock.tick(FPS)
                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":
            game.car.update(keys)
        
        # 更新游戏状态
        if game.game_state == "playing":
            game.update()
        
        # 绘制游戏
        game.draw(screen)
        
        pygame.display.flip()
    
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()