import pygame
import random
import time

# 初始化 Pygame
pygame.init()

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

# 屏幕设置
WIDTH = 400
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("2D 极速赛车")

clock = pygame.time.Clock()

# 赛车参数
CAR_WIDTH = 50
CAR_HEIGHT = 80

def draw_car(x, y):
    """绘制赛车（用矩形组合代替图片，方便直接运行）"""
    # 车身
    pygame.draw.rect(screen, RED, [x, y, CAR_WIDTH, CAR_HEIGHT])
    # 车窗
    pygame.draw.rect(screen, BLACK, [x + 10, y + 15, 30, 20])
    # 轮子
    pygame.draw.rect(screen, BLACK, [x - 5, y + 10, 5, 20])
    pygame.draw.rect(screen, BLACK, [x + CAR_WIDTH, y + 10, 5, 20])
    pygame.draw.rect(screen, BLACK, [x - 5, y + 50, 5, 20])
    pygame.draw.rect(screen, BLACK, [x + CAR_WIDTH, y + 50, 5, 20])

def draw_obstacle(ox, oy, ow, oh):
    """绘制障碍物"""
    pygame.draw.rect(screen, WHITE, [ox, oy, ow, oh])

def show_score(score):
    font = pygame.font.SysFont("SimHei", 25)
    text = font.render(f"得分: {score}", True, YELLOW)
    screen.blit(text, (10, 10))

def game_loop():
    x = WIDTH * 0.45
    y = HEIGHT * 0.8
    x_change = 0
    
    # 障碍物设置
    obs_start_x = random.randrange(0, WIDTH - CAR_WIDTH)
    obs_start_y = -600
    obs_speed = 5
    obs_width = 60
    obs_height = 60
    
    score = 0
    game_exit = False

    while not game_exit:
        # 1. 事件处理
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x_change = -7
                if event.key == pygame.K_RIGHT:
                    x_change = 7
            
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    x_change = 0

        # 2. 位置更新
        x += x_change
        screen.fill(GRAY) # 绘制背景（马路）

        # 绘制马路分界线
        pygame.draw.line(screen, YELLOW, (WIDTH/2, 0), (WIDTH/2, HEIGHT), 5)

        # 3. 绘制障碍物
        draw_obstacle(obs_start_x, obs_start_y, obs_width, obs_height)
        obs_start_y += obs_speed

        # 4. 绘制玩家赛车
        draw_car(x, y)
        show_score(score)

        # 5. 碰撞检测与边界检测
        # 撞墙
        if x < 0 or x > WIDTH - CAR_WIDTH:
            game_exit = True

        # 障碍物循环与加速
        if obs_start_y > HEIGHT:
            obs_start_y = 0 - obs_height
            obs_start_x = random.randrange(0, WIDTH - obs_width)
            score += 1
            obs_speed += 0.2 # 难度逐渐增加

        # 撞击障碍物检测
        if y < obs_start_y + obs_height:
            if (x > obs_start_x and x < obs_start_x + obs_width) or \
               (x + CAR_WIDTH > obs_start_x and x + CAR_WIDTH < obs_start_x + obs_width):
                game_exit = True

        pygame.display.update()
        clock.tick(60) # 60 帧

# 运行游戏
try:
    game_loop()
except Exception as e:
    print(f"游戏结束: {e}")
finally:
    pygame.quit()