import pygame
import random
import sys

# 初始化 pygame
pygame.init()

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

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

# 帧率
clock = pygame.time.Clock()
FPS = 60

# ===================== 游戏元素 =====================
# 玩家小车
player_size = 50
player_x = WIDTH // 2 - player_size // 2
player_y = HEIGHT - 120
player_speed = 8

# 障碍物（其他车辆）
obstacle_width = 50
obstacle_height = 60
obstacle_speed = 7
obstacles = []

# 道路背景滚动
road_y1 = 0
road_y2 = -HEIGHT
road_speed = 5

# 分数与游戏状态
score = 0
game_over = False
start_game = False

# 修复字体问题（关键修改）
def get_font(size):
    try:
        # 优先使用系统自带黑体，兼容性最强
        return pygame.font.SysFont("simhei", size)
    except:
        #  fallback 方案
        return pygame.font.Font(None, size)

font = get_font(50)
small_font = get_font(35)

# ===================== 函数 =====================
def draw_player(x, y):
    """绘制玩家小车"""
    pygame.draw.rect(screen, BLUE, (x, y, player_size, player_size))

def draw_obstacle(obstacle):
    """绘制障碍物"""
    pygame.draw.rect(screen, RED, obstacle)

def draw_road():
    """绘制滚动道路"""
    global road_y1, road_y2
    pygame.draw.rect(screen, GRAY, (100, 0, WIDTH - 200, HEIGHT))
    screen.blit(road_bg, (0, road_y1))
    screen.blit(road_bg, (0, road_y2))
    
    road_y1 += road_speed
    road_y2 += road_speed
    if road_y1 >= HEIGHT:
        road_y1 = -HEIGHT
    if road_y2 >= HEIGHT:
        road_y2 = -HEIGHT

# 创建道路背景
road_bg = pygame.Surface((WIDTH, HEIGHT))
road_bg.fill(GRAY)
pygame.draw.line(road_bg, WHITE, (WIDTH // 2, 0), (WIDTH // 2, HEIGHT), 5)

def show_text(text, x, y, color=WHITE, size="big"):
    """显示文字"""
    if size == "big":
        text_surface = font.render(text, True, color)
    else:
        text_surface = small_font.render(text, True, color)
    screen.blit(text_surface, (x, y))

def reset_game():
    """重置游戏"""
    global player_x, player_y, score, game_over, obstacles, start_game
    player_x = WIDTH // 2 - player_size // 2
    player_y = HEIGHT - 120
    score = 0
    game_over = False
    obstacles = []
    start_game = True

# ===================== 主循环 =====================
running = True
while running:
    clock.tick(FPS)
    screen.fill(BLACK)

    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        
        if event.type == pygame.KEYDOWN:
            if not start_game:
                reset_game()
            if game_over:
                if event.key == pygame.K_r:
                    reset_game()
            if event.key == pygame.K_ESCAPE:
                running = False

    if not start_game:
        # 开始界面
        show_text("驾驶小游戏", 120, 150, BLUE)
        show_text("按任意键开始", 120, 250)
        show_text("↑↓←→ 移动小车", 130, 320, WHITE, "small")
        pygame.display.update()
        continue

    if game_over:
        # 结束界面
        show_text("游戏结束!", 140, 200, RED)
        show_text(f"得分: {score}", 170, 270)
        show_text("按 R 重玩", 150, 340, GREEN)
        show_text("ESC 退出", 150, 400)
        pygame.display.update()
        continue

    # 绘制道路
    draw_road()

    # 玩家控制
    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP] and player_y > 100:
        player_y -= player_speed
    if keys[pygame.K_DOWN] and player_y < HEIGHT - player_size - 20:
        player_y += player_speed
    if keys[pygame.K_LEFT] and player_x > 120:
        player_x -= player_speed
    if keys[pygame.K_RIGHT] and player_x < WIDTH - 120 - player_size:
        player_x += player_speed

    # 生成障碍物
    if random.randint(1, 80) == 1:
        obs_x = random.randint(120, WIDTH - 120 - obstacle_width)
        obs_y = -obstacle_height
        obstacles.append([obs_x, obs_y, obstacle_width, obstacle_height])

    # 移动障碍物
    for obs in obstacles[:]:
        obs[1] += obstacle_speed
        if obs[1] > HEIGHT:
            obstacles.remove(obs)
            score += 1

    # 碰撞检测
    player_rect = pygame.Rect(player_x, player_y, player_size, player_size)
    for obs in obstacles:
        obs_rect = pygame.Rect(obs)
        if player_rect.colliderect(obs_rect):
            game_over = True

    # 绘制所有元素
    draw_player(player_x, player_y)
    for obs in obstacles:
        draw_obstacle(obs)

    # 显示分数
    show_text(f"得分: {score}", 20, 20, WHITE, "small")

    pygame.display.update()

pygame.quit()
sys.exit()