import pygame
import random
import sys

# --- 初始化 ---
pygame.init()

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

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

# 游戏参数
FPS = 60
CAR_WIDTH = 50
CAR_HEIGHT = 80

# --- 类定义 ---

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((CAR_WIDTH, CAR_HEIGHT))
        self.image.fill(BLUE)
        # 画一点装饰让它像车
        pygame.draw.rect(self.image, (100, 100, 255), (10, 10, 30, 20)) 
        self.rect = self.image.get_rect()
        self.rect.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT - 70)
        self.speed = 7

    def update(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] and self.rect.left > 50: # 50是草地边界
            self.rect.x -= self.speed
        if keys[pygame.K_RIGHT] and self.rect.right < SCREEN_WIDTH - 50:
            self.rect.x += self.speed

class Enemy(pygame.sprite.Sprite):
    def __init__(self, speed):
        super().__init__()
        self.image = pygame.Surface((CAR_WIDTH, CAR_HEIGHT))
        self.image.fill(RED)
        pygame.draw.rect(self.image, (255, 100, 100), (10, 50, 30, 20))
        self.rect = self.image.get_rect()
        # 随机在三条车道生成
        lane_positions = [80, 200, 320]
        self.rect.center = (random.choice(lane_positions), -100)
        self.speed = speed

    def update(self):
        self.rect.y += self.speed
        if self.rect.top > SCREEN_HEIGHT:
            self.kill() # 离开屏幕后销毁

# --- 辅助函数 ---

def draw_road():
    screen.fill((34, 139, 34)) # 绿色草地
    # 绘制公路
    pygame.draw.rect(screen, GRAY, (50, 0, SCREEN_WIDTH - 100, SCREEN_HEIGHT))
    # 绘制车道线
    for y in range(0, SCREEN_HEIGHT, 40):
        pygame.draw.line(screen, WHITE, (SCREEN_WIDTH//2, y), (SCREEN_WIDTH//2, y+20), 2)

def show_text(text, size, x, y):
    font = pygame.font.SysFont("SimHei", size)
    text_surface = font.render(text, True, WHITE)
    text_rect = text_surface.get_rect()
    text_rect.center = (x, y)
    screen.blit(text_surface, text_rect)

# --- 主循环 ---

def main():
    clock = pygame.time.Clock()
    player = Player()
    enemies = pygame.sprite.Group()
    all_sprites = pygame.sprite.Group()
    all_sprites.add(player)

    score = 0
    enemy_speed = 5
    spawn_timer = 0
    game_over = False

    while True:
        # 1. 事件处理
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN and game_over:
                main() # 游戏结束后按任意键重启

        if not game_over:
            # 2. 逻辑更新
            all_sprites.update()
            
            # 生成敌车
            spawn_timer += 1
            if spawn_timer > 40: # 每40帧尝试生成
                if len(enemies) < 4:
                    new_enemy = Enemy(enemy_speed)
                    # 简单防止重叠
                    if not pygame.sprite.spritecollide(new_enemy, enemies, False):
                        enemies.add(new_enemy)
                        all_sprites.add(new_enemy)
                spawn_timer = 0

            # 碰撞检测
            if pygame.sprite.spritecollide(player, enemies, False):
                game_over = True

            # 分数和难度增加
            score += 1
            if score % 500 == 0:
                enemy_speed += 1

        # 3. 渲染绘制
        draw_road()
        all_sprites.draw(screen)
        
        # 显示分数
        show_text(f"Score: {score}", 30, 70, 30)

        if game_over:
            pygame.draw.rect(screen, (0, 0, 0, 150), (50, 200, 300, 200))
            show_text("GAME OVER", 50, SCREEN_WIDTH//2, SCREEN_HEIGHT//2 - 20)
            show_text("Press Any Key to Restart", 20, SCREEN_WIDTH//2, SCREEN_HEIGHT//2 + 40)

        pygame.display.flip()
        clock.tick(FPS)

if __name__ == "__main__":
    main()