import pygame
import random
import math

# ===================== 基础配置 =====================
WIDTH, HEIGHT = 800, 600
FPS = 60
WHITE = (255, 255, 255)
GRAY = (80, 80, 80)  # 路面
GREEN = (34, 139, 34)  # 草地
RED = (200, 0, 0)
BLUE = (0, 0, 200)
BLACK = (0,0,0)

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("2D 赛车小游戏")
clock = pygame.time.Clock()

# 修复字体报错：使用默认渲染方式，避免SysFont系统字体bug
try:
    font = pygame.font.Font(None, 40)
except:
    # 兜底方案，极端环境兼容
    font = pygame.font.SysFont("simhei", 40, bold=True)

# ===================== 赛车类 =====================
class Car:
    def __init__(self, x, y, color, is_player=False):
        self.x = x
        self.y = y
        self.color = color
        self.angle = 0  # 旋转角度
        self.speed = 0
        self.max_speed = 6 if is_player else 3
        self.acc = 0.2
        self.friction = 0.05
        self.turn_speed = 2.8
        self.width = 24
        self.height = 48
        self.is_player = is_player

    def draw(self):
        # 创建赛车表面并旋转
        car_surf = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
        pygame.draw.rect(car_surf, self.color, (0, 0, self.width, self.height))
        pygame.draw.rect(car_surf, WHITE, (4, 8, 16, 8))
        rotated = pygame.transform.rotate(car_surf, -self.angle)
        rect = rotated.get_rect(center=(self.x, self.y))
        screen.blit(rotated, rect)

    def update(self):
        # 摩擦力减速
        if self.speed > 0:
            self.speed -= self.friction
        elif self.speed < 0:
            self.speed += self.friction

        # 速度限制
        self.speed = max(-self.max_speed//2, min(self.speed, self.max_speed))

        # 位移计算
        rad = math.radians(self.angle)
        self.x += math.sin(rad) * self.speed
        self.y -= math.cos(rad) * self.speed

        # 赛道左右边界
        road_left = 150
        road_right = WIDTH - 150
        if self.x < road_left:
            self.x = road_left
            self.speed *= -0.5
        if self.x > road_right:
            self.x = road_right
            self.speed *= -0.5
        # 上下屏幕边界
        if self.y < -50:
            self.y = -50
        if self.y > HEIGHT + 50:
            self.y = HEIGHT + 50

# ===================== 生成AI车辆 =====================
def create_ai_cars(num=6):
    ai_list = []
    for _ in range(num):
        x = random.randint(200, WIDTH-200)
        y = random.randint(-300, HEIGHT)
        color = (random.randint(50, 255), random.randint(50, 255), random.randint(50, 255))
        car = Car(x, y, color, is_player=False)
        car.angle = 0
        car.speed = random.uniform(1.5, 3)
        ai_list.append(car)
    return ai_list

# ===================== 游戏主逻辑 =====================
def main():
    player = Car(WIDTH//2, HEIGHT-100, RED, is_player=True)
    ai_cars = create_ai_cars()
    score = 0
    running = True

    while running:
        clock.tick(FPS)
        screen.fill(GREEN)

        # 绘制赛道（中间灰色直道）
        pygame.draw.rect(screen, GRAY, (150, 0, WIDTH-300, HEIGHT))

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

        # 玩家按键控制
        keys = pygame.key.get_pressed()
        # 前进
        if keys[pygame.K_UP]:
            player.speed += player.acc
        # 后退
        if keys[pygame.K_DOWN]:
            player.speed -= player.acc
        # 左转（只有有速度才能转弯）
        if keys[pygame.K_LEFT] and abs(player.speed) > 0.1:
            player.angle += player.turn_speed * (player.speed / player.max_speed)
        # 右转
        if keys[pygame.K_RIGHT] and abs(player.speed) > 0.1:
            player.angle -= player.turn_speed * (player.speed / player.max_speed)

        # 更新玩家赛车
        player.update()
        player.draw()

        # 更新AI车辆
        for car in ai_cars:
            car.update()
            car.draw()
            # AI驶出屏幕底部，重置到上方循环
            if car.y > HEIGHT + 50:
                car.y = random.randint(-200, -50)
                car.x = random.randint(200, WIDTH-200)

        # 计分渲染
        score_text = font.render(f"分数: {int(score)}", True, WHITE)
        screen.blit(score_text, (20, 20))

        pygame.display.flip()

    pygame.quit()

if __name__ == "__main__":
    main()