import pygame
import random
import sys
import os

# 初始化Pygame
pygame.init()

# 窗口基础设置
WIDTH = 400
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("简易驾驶小游戏")

# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (80, 80, 80)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
YELLOW = (255, 255, 0)

# 车道划分
lane_width = WIDTH // 4
# 玩家车辆参数
car_width = 40
car_height = 80
player_x = WIDTH // 2 - car_width // 2
player_y = HEIGHT - car_height - 20
player_speed = 7

# 敌方车辆列表
enemy_cars = []
enemy_speed = 5
spawn_timer = 0
score = 0

# ========== 修复字体部分，使用Windows自带黑体路径，不会缺文件 ==========
try:
    # Windows系统默认黑体路径，绝大多数电脑都存在
    font_path = r"C:\Windows\Fonts\simhei.ttf"
    font = pygame.font.Font(font_path, 30)
except Exception:
    # 兜底使用最简单方式创建字体，规避SysFont报错
    font = pygame.font.Font(None, 30)

# 游戏状态
game_over = False
clock = pygame.time.Clock()
FPS = 60

def reset_game():
    """重置游戏所有数据"""
    global player_x, player_y, enemy_cars, score, game_over, enemy_speed
    player_x = WIDTH // 2 - car_width // 2
    player_y = HEIGHT - car_height - 20
    enemy_cars.clear()
    score = 0
    enemy_speed = 5
    game_over = False

# 主游戏循环
while True:
    clock.tick(FPS)
    screen.fill(GRAY)

    # 绘制道路白色分隔线
    for i in range(1, 4):
        pygame.draw.rect(screen, WHITE, (i * lane_width - 2, 0, 4, HEIGHT))

    # 事件监听
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        # 游戏结束按空格重新开始
        if event.type == pygame.KEYDOWN and game_over:
            if event.key == pygame.K_SPACE:
                reset_game()

    if not game_over:
        # 按键左右移动
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] and player_x > 5:
            player_x -= player_speed
        if keys[pygame.K_RIGHT] and player_x < WIDTH - car_width - 5:
            player_x += player_speed

        # 随机生成敌方车辆
        spawn_timer += 1
        if spawn_timer > 45:
            spawn_timer = 0
            # 随机车道
            rand_lane = random.randint(0, 3)
            ex = rand_lane * lane_width + (lane_width - car_width) // 2
            enemy_cars.append([ex, -car_height])

        # 更新敌方车辆位置
        for car in enemy_cars:
            car[1] += enemy_speed

        # 移除跑出屏幕的车辆并加分
        for idx in range(len(enemy_cars)-1, -1, -1):
            if enemy_cars[idx][1] > HEIGHT:
                enemy_cars.pop(idx)
                score += 1
                # 分数越高难度越快
                if score % 5 == 0:
                    enemy_speed += 0.3

        # 碰撞检测
        player_rect = pygame.Rect(player_x, player_y, car_width, car_height)
        for car in enemy_cars:
            enemy_rect = pygame.Rect(car[0], car[1], car_width, car_height)
            if player_rect.colliderect(enemy_rect):
                game_over = True

    # 绘制玩家赛车（红色）
    pygame.draw.rect(screen, RED, (player_x, player_y, car_width, car_height))
    # 车头装饰
    pygame.draw.rect(screen, YELLOW, (player_x+8, player_y+5, car_width-16, 12))

    # 绘制敌方车辆（绿色）
    for car in enemy_cars:
        pygame.draw.rect(screen, GREEN, (car[0], car[1], car_width, car_height))

    # 绘制分数
    score_text = font.render(f"得分：{score}", True, WHITE)
    screen.blit(score_text, (10, 10))

    # 游戏结束界面
    if game_over:
        over_text1 = font.render("游戏碰撞结束！", True, RED)
        over_text2 = font.render("按空格键重新开始", True, WHITE)
        screen.blit(over_text1, (WIDTH//2 - 120, HEIGHT//2 - 40))
        screen.blit(over_text2, (WIDTH//2 - 145, HEIGHT//2 + 10))

    pygame.display.update()
