import pygame
import random

pygame.init()
# 窗口设置
WIDTH, HEIGHT = 480, 700
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("驾驶小游戏")

# 颜色定义
BG_ROAD = (40, 40, 40)        # 道路颜色
LINE_COLOR = (220, 180, 0)    # 道路标线
PLAYER_CAR = (50,160,220)     # 自己的车颜色
ENEMY_CAR = (200,40,40)       # 敌方车辆
WHITE = (255, 255, 255)
RED = (255,0,0)

clock = pygame.time.Clock()
FPS = 60

# --------修改关键点：使用None代替字体名称，绕过系统字体加载错误----------
font = pygame.font.Font(None,30)

# 玩家车辆参数
car_w = 60
car_h = 100
player_x = WIDTH // 2 - car_w // 2
player_y = HEIGHT - 130
speed = 7

# 对面车辆列表
enemies = []
enemy_speed = 5
score = 0

def create_enemy():
    """生成敌方车辆"""
    x_pos = random.choice([40,150,260,370])
    enemy_y = random.randint(-150,-80)
    enemies.append([x_pos, enemy_y])

running = True
while running:
    clock.tick(FPS)
    screen.fill(BG_ROAD)
    # 绘制车道虚线
    for y in range(0, HEIGHT, 80):
        pygame.draw.rect(screen, LINE_COLOR, [WIDTH//2 - 4, y, 8, 40])

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

    # 按键移动
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and player_x > 20:
        player_x -= speed
    if keys[pygame.K_RIGHT] and player_x < WIDTH - car_w -20:
        player_x += speed
    if keys[pygame.K_UP] and player_y > 10:
        player_y -= speed
    if keys[pygame.K_DOWN] and player_y < HEIGHT - car_h - 10:
        player_y += speed

    # 随机产生来车
    if random.randint(1,70) == 1:
        create_enemy()

    # 更新敌方车辆
    for car in enemies[:]:
        car[1] += enemy_speed
        pygame.draw.rect(screen, ENEMY_CAR, (car[0], car[1], car_w, car_h))
        if car[1] > HEIGHT:
            enemies.remove(car)
            score +=10
        # 碰撞判断
        player_rect = pygame.Rect(player_x, player_y, car_w, car_h)
        enemy_rect = pygame.Rect(car[0], car[1], car_w, car_h)
        if player_rect.colliderect(enemy_rect):
            game_over_text = font.render(f"Game Over! Score:{score}",True,RED)
            screen.blit(game_over_text,(80,HEIGHT//2))
            pygame.display.update()
            pygame.time.wait(2000)
            running = False

    # 绘制自己的车
    pygame.draw.rect(screen, PLAYER_CAR, (player_x, player_y, car_w, car_h))

    # 显示分数（改成英文避免中文乱码问题，如果后面需要中文我再给你写备用方案）
    score_text = font.render(f"Score: {score}", True, WHITE)
    screen.blit(score_text,(10,10))

    pygame.display.flip()

pygame.quit()
     