import pygame
import random
import sys
import os

# 初始化pygame
pygame.init()

# 游戏窗口设置
WIDTH, HEIGHT = 800, 600
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("极速驾驶 - 躲避挑战")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 120, 255)
YELLOW = (255, 255, 0)
GRAY = (100, 100, 100)
DARK_GRAY = (50, 50, 50)
ROAD_COLOR = (40, 40, 40)

# 创建字体
def create_fonts():
    """创建不同大小的字体，优先使用系统黑体"""
    fonts = {}
    sizes = [24, 36, 48, 72]
    
    # Windows系统的黑体常见路径
    font_paths = [
        "C:/Windows/Fonts/simhei.ttf",  # Windows
        "C:/Windows/Fonts/msyh.ttc"   # Windows 微软雅黑

    ]
    
    # 首先尝试加载系统字体名称
    system_font_names = ["SimHei", "Microsoft YaHei", "Arial", "sans-serif"]
    
    for size in sizes:
        font_loaded = False
        
        # 方法1: 尝试通过系统字体名称
        for font_name in system_font_names:
            try:
                fonts[size] = pygame.font.SysFont(font_name, size)
                print(f"成功加载系统字体: {font_name}, 大小: {size}")
                font_loaded = True
                break
            except:
                continue
        
        # 方法2: 如果方法1失败，尝试从文件路径加载
        if not font_loaded:
            for font_path in font_paths:
                try:
                    if os.path.exists(font_path):
                        fonts[size] = pygame.font.Font(font_path, size)
                        print(f"成功从文件加载字体: {font_path}, 大小: {size}")
                        font_loaded = True
                        break
                except:
                    continue
        
        # 方法3: 如果以上都失败，使用默认字体
        if not font_loaded:
            fonts[size] = pygame.font.Font(None, size)
            print(f"使用默认字体, 大小: {size}")
    
    return fonts

# 加载所有字体
fonts = create_fonts()

# 字体快捷方式
def get_font(size):
    return fonts.get(size, pygame.font.Font(None, size))

# 游戏时钟
FPS = 60
clock = pygame.time.Clock()

# 玩家车辆类
class PlayerCar:
    def __init__(self):
        self.width = 60
        self.height = 100
        self.x = WIDTH // 2 - self.width // 2
        self.y = HEIGHT - 150
        self.speed = 8
        self.color = BLUE
        self.lives = 3
    
    def draw(self, surface):
        # 绘制车体
        pygame.draw.rect(surface, self.color, (self.x, self.y, self.width, self.height), 0, 10)
        
        # 绘制车窗
        pygame.draw.rect(surface, (200, 230, 255), 
                         (self.x + 10, self.y + 10, self.width - 20, 30), 0, 5)
        
        # 绘制车轮
        pygame.draw.rect(surface, BLACK, (self.x - 5, self.y + 20, 10, 20), 0, 3)
        pygame.draw.rect(surface, BLACK, (self.x + self.width - 5, self.y + 20, 10, 20), 0, 3)
        pygame.draw.rect(surface, BLACK, (self.x - 5, self.y + self.height - 40, 10, 20), 0, 3)
        pygame.draw.rect(surface, BLACK, (self.x + self.width - 5, self.y + self.height - 40, 10, 20), 0, 3)
    
    def move(self, keys):
        if keys[pygame.K_LEFT] and self.x > 150:
            self.x -= self.speed
        if keys[pygame.K_RIGHT] and self.x < WIDTH - 150 - self.width:
            self.x += self.speed
        if keys[pygame.K_UP] and self.y > 100:
            self.y -= self.speed
        if keys[pygame.K_DOWN] and self.y < HEIGHT - 50 - self.height:
            self.y += self.speed

# 障碍车辆类
class ObstacleCar:
    def __init__(self):
        self.width = random.randint(50, 70)
        self.height = random.randint(80, 120)
        self.x = random.randint(150, WIDTH - 150 - self.width)
        self.y = -self.height
        self.speed = random.randint(3, 7)
        self.color = random.choice([RED, GREEN, YELLOW, (255, 150, 0), (200, 0, 200)])
    
    def move(self):
        self.y += self.speed
    
    def draw(self, surface):
        pygame.draw.rect(surface, self.color, (self.x, self.y, self.width, self.height), 0, 8)
        
        # 简单车窗
        pygame.draw.rect(surface, (230, 230, 230), 
                         (self.x + 8, self.y + 8, self.width - 16, 20), 0, 4)
    
    def is_off_screen(self):
        return self.y > HEIGHT

# 道路标记
class RoadMark:
    def __init__(self, y):
        self.width = 20
        self.height = 60
        self.x = WIDTH // 2 - self.width // 2
        self.y = y
        self.speed = 5
    
    def move(self):
        self.y += self.speed
    
    def draw(self, surface):
        pygame.draw.rect(surface, YELLOW, (self.x, self.y, self.width, self.height))
    
    def is_off_screen(self):
        return self.y > HEIGHT

# 碰撞检测
def check_collision(player, obstacle):
    player_rect = pygame.Rect(player.x, player.y, player.width, player.height)
    obstacle_rect = pygame.Rect(obstacle.x, obstacle.y, obstacle.width, obstacle.height)
    return player_rect.colliderect(obstacle_rect)

# 绘制道路
def draw_road(surface):
    # 道路背景
    pygame.draw.rect(surface, ROAD_COLOR, (150, 0, WIDTH - 300, HEIGHT))
    
    # 道路边缘
    pygame.draw.rect(surface, DARK_GRAY, (140, 0, 10, HEIGHT))
    pygame.draw.rect(surface, DARK_GRAY, (WIDTH - 150, 0, 10, HEIGHT))
    
    # 道路边线
    pygame.draw.rect(surface, WHITE, (145, 0, 5, HEIGHT))
    pygame.draw.rect(surface, WHITE, (WIDTH - 150, 0, 5, HEIGHT))

# 绘制UI
def draw_ui(surface, score, lives, level):
    # 绘制分数
    score_text = get_font(36).render(f"分数: {score}", True, WHITE)
    surface.blit(score_text, (20, 20))
    
    # 绘制生命值
    lives_text = get_font(36).render(f"生命: {lives}", True, WHITE)
    surface.blit(lives_text, (20, 60))
    
    # 绘制等级
    level_text = get_font(36).render(f"等级: {level}", True, WHITE)
    surface.blit(level_text, (20, 100))
    
    # 绘制控制说明
    controls = ["控制: ↑ ↓ ← → 移动", "目标: 躲避其他车辆"]
    for i, text in enumerate(controls):
        control_text = get_font(24).render(text, True, YELLOW)
        surface.blit(control_text, (WIDTH - 250, 20 + i * 30))

# 开始游戏画面
def start_screen(surface):
    surface.fill((0, 100, 0))  # 绿色背景
    
    # 绘制道路
    draw_road(surface)
    
    # 游戏标题
    title_text = get_font(72).render("极速驾驶", True, YELLOW)
    surface.blit(title_text, (WIDTH//2 - title_text.get_width()//2, 100))
    
    # 游戏说明
    instruction1 = get_font(36).render("躲避其他车辆，获得高分！", True, WHITE)
    instruction2 = get_font(36).render("使用方向键控制车辆移动", True, WHITE)
    instruction3 = get_font(36).render("按空格键开始游戏", True, GREEN)
    
    surface.blit(instruction1, (WIDTH//2 - instruction1.get_width()//2, 250))
    surface.blit(instruction2, (WIDTH//2 - instruction2.get_width()//2, 300))
    surface.blit(instruction3, (WIDTH//2 - instruction3.get_width()//2, 350))
    
    # 绘制示例车辆
    player_example = PlayerCar()
    player_example.x = WIDTH // 2 - player_example.width // 2
    player_example.y = 400
    player_example.draw(surface)
    
    pygame.display.update()

# 游戏结束画面
def game_over_screen(surface, score):
    overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
    overlay.fill((0, 0, 0, 200))
    surface.blit(overlay, (0, 0))
    
    game_over = get_font(72).render("游戏结束", True, RED)
    score_text = get_font(48).render(f"最终分数: {score}", True, WHITE)
    restart_text = get_font(36).render("按R键重新开始，按ESC退出", True, YELLOW)
    
    surface.blit(game_over, (WIDTH//2 - game_over.get_width()//2, HEIGHT//2 - 100))
    surface.blit(score_text, (WIDTH//2 - score_text.get_width()//2, HEIGHT//2))
    surface.blit(restart_text, (WIDTH//2 - restart_text.get_width()//2, HEIGHT//2 + 100))

# 主游戏函数
def main_game_loop():
    player = PlayerCar()
    obstacles = []
    road_marks = []
    
    score = 0
    level = 1
    obstacle_spawn_timer = 0
    road_mark_timer = 0
    game_over = False
    game_started = False
    
    # 初始道路标记
    for i in range(0, HEIGHT, 120):
        road_marks.append(RoadMark(i))
    
    # 显示开始画面
    start_screen(WIN)
    
    # 等待开始
    waiting = True
    while waiting:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    waiting = False
                    game_started = True
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
    
    # 游戏主循环
    running = True
    while running:
        clock.tick(FPS)
        
        # 事件处理
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
                if game_over and event.key == pygame.K_r:
                    # 重新开始游戏
                    return main_game_loop()
                if not game_over and event.key == pygame.K_p:
                    # 暂停功能
                    paused = True
                    pause_font = get_font(48)
                    while paused:
                        for pause_event in pygame.event.get():
                            if pause_event.type == pygame.QUIT:
                                pygame.quit()
                                sys.exit()
                            if pause_event.type == pygame.KEYDOWN and pause_event.key == pygame.K_p:
                                paused = False
                        pause_text = pause_font.render("游戏暂停 - 按P继续", True, YELLOW)
                        WIN.blit(pause_text, (WIDTH//2 - pause_text.get_width()//2, HEIGHT//2))
                        pygame.display.update()
                        clock.tick(5)  # 降低暂停时的CPU使用率
        
        if game_started and not game_over:
            # 玩家移动
            keys = pygame.key.get_pressed()
            player.move(keys)
            
            # 生成障碍车辆
            obstacle_spawn_timer += 1
            spawn_interval = 60 - min(level * 3, 40)
            if obstacle_spawn_timer > spawn_interval:
                obstacles.append(ObstacleCar())
                obstacle_spawn_timer = 0
            
            # 生成道路标记
            road_mark_timer += 1
            if road_mark_timer > 30:
                road_marks.append(RoadMark(-60))
                road_mark_timer = 0
            
            # 移动障碍车辆
            for obstacle in obstacles[:]:
                obstacle.move()
                if obstacle.is_off_screen():
                    obstacles.remove(obstacle)
                    score += 10
            
            # 移动道路标记
            for mark in road_marks[:]:
                mark.move()
                if mark.is_off_screen():
                    road_marks.remove(mark)
            
            # 碰撞检测
            for obstacle in obstacles[:]:
                if check_collision(player, obstacle):
                    player.lives -= 1
                    obstacles.remove(obstacle)
                    if player.lives <= 0:
                        game_over = True
            
            # 升级逻辑
            level = score // 100 + 1
        
        # 绘制
        WIN.fill((0, 100, 0))  # 绿色背景（草地）
        
        # 绘制道路
        draw_road(WIN)
        
        # 绘制道路标记
        for mark in road_marks:
            mark.draw(WIN)
        
        # 绘制障碍车辆
        for obstacle in obstacles:
            obstacle.draw(WIN)
        
        # 绘制玩家车辆
        player.draw(WIN)
        
        # 绘制UI
        draw_ui(WIN, score, player.lives, level)
        
        # 绘制暂停提示
        if not game_over:
            pause_hint = get_font(24).render("按P暂停游戏", True, WHITE)
            WIN.blit(pause_hint, (WIDTH - pause_hint.get_width() - 20, HEIGHT - 40))
        
        # 游戏结束画面
        if game_over:
            game_over_screen(WIN, score)
        
        pygame.display.update()
    
    pygame.quit()
    sys.exit()

# 启动游戏
if __name__ == "__main__":
    main_game_loop()