import pygame
import random
import sys

# 初始化pygame
pygame.init()

# 窗口设置
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("2D赛车游戏")

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

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

# 玩家赛车
player_width = 50
player_height = 100
player_x = SCREEN_WIDTH // 2 - player_width // 2
player_y = SCREEN_HEIGHT - player_height - 20
player_speed = 7

# 车道
road_left = 50
road_right = SCREEN_WIDTH - 50
lane_width = (road_right - road_left) // 3

# 敌人车辆
enemy_list = []
enemy_width = 50
enemy_height = 100
enemy_speed = 5
spawn_rate = 1500  # 生成间隔毫秒
last_spawn = pygame.time.get_ticks()

# 路面标线
line_y = 0
line_speed = 8

# 分数
score = 0
# 字体，优先黑体，失败则使用默认字体
try:
    font = pygame.font.SysFont("simhei", 32)
    over_font = pygame.font.SysFont("simhei", 48)
    tip_font = pygame.font.SysFont("simhei", 28)
except:
    font = pygame.font.Font(None,32)
    over_font = pygame.font.Font(None,48)
    tip_font = pygame.font.Font(None,28)


def create_enemy():
    """生成敌方车辆"""
    lane = random.randint(0, 2)
    x = road_left + lane * lane_width + (lane_width - enemy_width) // 2
    y = -enemy_height
    enemy_list.append([x, y])


def draw_road():
    """绘制道路和草地"""
    screen.fill(GREEN)
    # 路面
    pygame.draw.rect(screen, GRAY, (road_left, 0, road_right - road_left, SCREEN_HEIGHT))
    # 车道白线
    global line_y
    line_y += line_speed
    if line_y > 40:
        line_y = 0
    for y in range(line_y, SCREEN_HEIGHT, 80):
        pygame.draw.rect(screen, WHITE, (road_left + lane_width - 3, y, 6, 30))
        pygame.draw.rect(screen, WHITE, (road_left + lane_width * 2 - 3, y, 6, 30))
    # 道路边界黄线
    pygame.draw.rect(screen, YELLOW, (road_left - 5, 0, 5, SCREEN_HEIGHT))
    pygame.draw.rect(screen, YELLOW, (road_right, 0, 5, SCREEN_HEIGHT))


def draw_car(x, y, w, h, color):
    """绘制简单车辆"""
    pygame.draw.rect(screen, color, (x, y, w, h))
    pygame.draw.rect(screen, BLACK, (x + 5, y + 10, w - 10, 15))
    pygame.draw.rect(screen, BLACK, (x + 5, y + h - 25, w - 10, 15))


def show_score():
    text = font.render(f"分数: {score}", True, WHITE)
    screen.blit(text, (10, 10))


def game_over():
    text1 = over_font.render("游戏结束!", True, RED)
    text2 = tip_font.render("按R重新开始 | Q退出", True, WHITE)
    screen.blit(text1, (SCREEN_WIDTH//2 - 100, SCREEN_HEIGHT//2 - 50))
    screen.blit(text2, (SCREEN_WIDTH//2 - 140, SCREEN_HEIGHT//2 + 10))
    pygame.display.update()
    while True:
        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_r:
                    return True
                if event.key == pygame.K_q:
                    pygame.quit()
                    sys.exit()


# 主游戏循环
running = True
game_state = "play"

while running:
    clock.tick(FPS)
    current_time = pygame.time.get_ticks()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    if game_state == "play":
        # 玩家控制
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] and player_x > road_left:
            player_x -= player_speed
        if keys[pygame.K_RIGHT] and player_x + player_width < road_right:
            player_x += player_speed

        # 生成敌方车
        if current_time - last_spawn > spawn_rate:
            create_enemy()
            last_spawn = current_time
            # 随分数提高难度
            enemy_speed = 5 + score // 300

        # 更新敌人
        for enemy in enemy_list[:]:
            enemy[1] += enemy_speed
            if enemy[1] > SCREEN_HEIGHT:
                enemy_list.remove(enemy)
                score += 10

        # 碰撞检测
        player_rect = pygame.Rect(player_x, player_y, player_width, player_height)
        crash = False
        for enemy in enemy_list:
            enemy_rect = pygame.Rect(enemy[0], enemy[1], enemy_width, enemy_height)
            if player_rect.colliderect(enemy_rect):
                crash = True
                break
        if crash:
            game_state = "over"

        # 绘制
        draw_road()
        draw_car(player_x, player_y, player_width, player_height, (0, 120, 255))
        for enemy in enemy_list:
            draw_car(enemy[0], enemy[1], enemy_width, enemy_height, (200, 0, 0))
        show_score()

    elif game_state == "over":
        restart = game_over()
        if restart:
            # 重置游戏
            player_x = SCREEN_WIDTH // 2 - player_width // 2
            player_y = SCREEN_HEIGHT - player_height - 20
            enemy_list.clear()
            score = 0
            enemy_speed = 5
            game_state = "play"

    pygame.display.flip()

pygame.quit()
sys.exit()
