import pygame
import math

# 初始化Pygame
pygame.init()

# 游戏设置
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("2D赛车游戏")
clock = pygame.time.Clock()
FPS = 60

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (34, 139, 34)  # 赛道颜色
RED = (255, 0, 0)      # 赛车颜色
GRAY = (100, 100, 100) # 边界颜色
BLUE = (0, 0, 255)     # 终点线颜色

# 赛道定义（由多个矩形段组成，格式：(x, y, width, height)）
track_segments = [
    # 直道1
    (300, 50, 200, 200),
    # 右弯道（简化为矩形拼接）
    (300, 250, 300, 150),
    # 直道2
    (400, 400, 200, 200),
    # 左弯道
    (100, 400, 300, 150),
    # 终点直道
    (100, 100, 200, 200)
]

# 赛车类
class Car:
    def __init__(self, x, y):
        # 位置和尺寸
        self.x = x
        self.y = y
        self.width = 40
        self.height = 20
        
        # 运动参数
        self.angle = 0  # 朝向角度（0为向上）
        self.speed = 0
        self.max_speed = 8
        self.acceleration = 0.2
        self.deceleration = 0.1
        self.turn_speed = 3  # 转向速度（度/帧）
        
        # 碰撞盒（简化为矩形）
        self.rect = pygame.Rect(self.x - self.width/2, self.y - self.height/2, self.width, self.height)
    
    def update(self, keys, track_segments):
        """更新赛车状态（操控+碰撞）"""
        # 加速/减速
        if keys[pygame.K_UP]:
            self.speed += self.acceleration
        elif keys[pygame.K_DOWN]:
            self.speed -= self.acceleration
        else:
            # 自然减速（摩擦力）
            if self.speed > 0:
                self.speed -= self.deceleration
            elif self.speed < 0:
                self.speed += self.deceleration
        
        # 限制速度范围
        self.speed = max(-self.max_speed/2, min(self.speed, self.max_speed))
        
        # 转向（只有有速度时才能转向）
        if keys[pygame.K_LEFT] and self.speed != 0:
            self.angle += self.turn_speed * (self.speed / self.max_speed)
        if keys[pygame.K_RIGHT] and self.speed != 0:
            self.angle -= self.turn_speed * (self.speed / self.max_speed)
        
        # 计算位移（基于朝向和速度）
        rad = math.radians(self.angle)
        dx = math.sin(rad) * self.speed
        dy = -math.cos(rad) * self.speed  # y轴向下，所以取负
        
        # 临时位置（用于碰撞检测）
        temp_x = self.x + dx
        temp_y = self.y + dy
        
        # 碰撞检测：检查是否在赛道内
        temp_rect = pygame.Rect(temp_x - self.width/2, temp_y - self.height/2, self.width, self.height)
        on_track = False
        for seg in track_segments:
            seg_rect = pygame.Rect(seg)
            if seg_rect.colliderect(temp_rect):
                on_track = True
                break
        
        # 只有在赛道内才更新位置
        if on_track:
            self.x = temp_x
            self.y = temp_y
        else:
            self.speed *= -0.3  # 碰撞后回弹减速
        
        # 更新碰撞盒位置
        self.rect.center = (self.x, self.y)
    
    def draw(self, surface, camera_x, camera_y):
        """绘制赛车（考虑相机偏移）"""
        # 旋转赛车（Pygame旋转精灵的标准方法）
        car_surf = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
        car_surf.fill(RED)
        rotated_surf = pygame.transform.rotate(car_surf, self.angle)
        rotated_rect = rotated_surf.get_rect(center=(self.x - camera_x, self.y - camera_y))
        surface.blit(rotated_surf, rotated_rect)

# 相机类（跟随赛车）
class Camera:
    def __init__(self, width, height):
        self.x = 0
        self.y = 0
        self.width = width
        self.height = height
    
    def follow(self, car):
        """跟随赛车移动，保持赛车在屏幕中心"""
        self.x = car.x - self.width/2
        self.y = car.y - self.height/2
        
        # 限制相机不超出赛道范围（可选）
        self.x = max(0, min(self.x, 800 - self.width))
        self.y = max(0, min(self.y, 800 - self.height))

# 初始化赛车和相机
car = Car(350, 100)  # 初始位置在第一条直道
camera = Camera(WINDOW_WIDTH, WINDOW_HEIGHT)

# 游戏主循环
running = True
while running:
    # 控制帧率
    clock.tick(FPS)
    
    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    # 获取键盘输入
    keys = pygame.key.get_pressed()
    
    # 更新游戏逻辑
    car.update(keys, track_segments)
    camera.follow(car)
    
    # 绘制画面
    screen.fill(BLACK)  # 背景（赛道外的区域）
    
    # 绘制赛道（考虑相机偏移）
    for seg in track_segments:
        seg_rect = pygame.Rect(seg)
        draw_rect = pygame.Rect(
            seg_rect.x - camera.x,
            seg_rect.y - camera.y,
            seg_rect.width,
            seg_rect.height
        )
        pygame.draw.rect(screen, GREEN, draw_rect)  # 赛道主体
        pygame.draw.rect(screen, GRAY, draw_rect, 2)  # 赛道边界
    
    # 绘制终点线（第一条直道末端）
    finish_line = pygame.Rect(300, 240, 200, 5)
    draw_finish = pygame.Rect(
        finish_line.x - camera.x,
        finish_line.y - camera.y,
        finish_line.width,
        finish_line.height
    )
    pygame.draw.rect(screen, BLUE, draw_finish)
    
    # 绘制赛车
    car.draw(screen, camera.x, camera.y)
    
    # 显示速度信息
    font = pygame.font.SysFont(None, 36)
    speed_text = font.render(f"速度: {int(abs(car.speed)*10)} km/h", True, WHITE)
    screen.blit(speed_text, (10, 10))
    
    # 更新屏幕
    pygame.display.flip()

# 退出游戏
pygame.quit()