import pygame
import random

# 初始化
pygame.init()
W, H = 400, 600
screen = pygame.display.set_mode((W, H))
pygame.display.set_caption("Pygame 2D 赛车")
clock = pygame.time.Clock()
FPS = 60

# 颜色定义
BG = (50, 50, 50)
ROAD = (80, 80, 80)
LINE = (255, 255, 255)
PLAYER_COL = (0, 255, 0)
ENEMY_COL = (255, 0, 0)
TEXT_COLOR = (255, 255, 255)

# 车辆尺寸
pw, ph = 50, 80
px = W // 2 - pw // 2
py = H - ph - 20
ps = 5

ew, eh = 50, 80
es = 5
elist = []
spawn_rate = 1500
last_spawn = 0

# 道路标线
line_y = 0
line_speed = 5

# 分数与难度
score = 0
speed_up = 0

# ========== 修复字体报错：改用默认渲染字体 ==========
font = pygame.font.Font(None, 36)

# 绘制玩家车辆
def draw_player(x, y):
    pygame.draw.rect(screen, PLAYER_COL, (x, y, pw, ph))

# 绘制敌方车辆
def draw_enemy(enemies):
    for e in enemies:
        pygame.draw.rect(screen, ENEMY_COL, (e[0], e[1], ew, eh))

# 绘制滚动道路
def draw_road():
    screen.fill(BG)
    pygame.draw.rect(screen, ROAD, (50, 0, 300, H))
    global line_y
    line_y += line_speed
    if line_y > H:
        line_y = -20
    for i in range(3):
        pygame.draw.rect(screen, LINE, (100 + i * 100, line_y, 5, 40))

# 显示分数
def show_score(s):
    txt = font.render(f"Score: {s}", True, TEXT_COLOR)
    screen.blit(txt, (10, 10))

# 游戏结束界面
def game_over(score):
    txt = font.render(f"GAME OVER! Score: {score}", True, TEXT_COLOR)
    screen.blit(txt, (W // 2 - 120, H // 2))
    pygame.display.update()
    pygame.time.wait(2000)

# 主循环
running = True
gameover = False
while running:
    clock.tick(FPS)
    now = pygame.time.get_ticks()

    # 事件监听
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    if not gameover:
        # 左右移动控制
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] and px > 60:
            px -= ps
        if keys[pygame.K_RIGHT] and px < W - 60 - pw:
            px += ps

        # 生成敌车
        if now - last_spawn > spawn_rate:
            ex = random.choice([75, 175, 275])
            elist.append([ex, -eh])
            last_spawn = now

        # 敌车移动+销毁
        for i in range(len(elist)-1, -1, -1):
            elist[i][1] += es
            if elist[i][1] > H:
                elist.pop(i)
                score += 10

        # 碰撞检测
        player_rect = pygame.Rect(px, py, pw, ph)
        for e in elist:
            enemy_rect = pygame.Rect(e[0], e[1], ew, eh)
            if player_rect.colliderect(enemy_rect):
                gameover = True
                game_over(score)

        # 难度递增
        speed_up += 1
        if speed_up % 500 == 0:
            es += 0.5
            line_speed += 0.2
            spawn_rate = max(500, spawn_rate - 50)

    # 画面渲染
    draw_road()
    draw_player(px, py)
    draw_enemy(elist)
    show_score(score)
    pygame.display.update()

pygame.quit()