import pygame
import sys
import random

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

WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("2D 赛车游戏（带 UI）")

clock = pygame.time.Clock()
font = pygame.font.Font(None, 36)  # ✅ 用 None，绝对不报错

# ================== 颜色 ==================
WHITE = (255, 255, 255)
GRAY = (40, 40, 40)
RED = (220, 50, 50)
GREEN = (50, 200, 50)
BLACK = (0, 0, 0)

# ================== 游戏状态 ==================
MENU = 0
PLAYING = 1
GAME_OVER = 2
state = MENU


# ================== 玩家赛车 ==================
class PlayerCar:
    def __init__(self):
        self.x = WIDTH // 2
        self.y = HEIGHT - 120
        self.speed = 0
        self.max_speed = 8
        self.acc = 0.3
        self.friction = 0.1
        self.w = 40
        self.h = 70

    def update(self, keys):
        if keys[pygame.K_UP]:
            self.speed += self.acc
        elif keys[pygame.K_DOWN]:
            self.speed -= self.acc
        else:
            self.speed *= 0.95

        self.speed = max(-3, min(self.max_speed, self.speed))

        if keys[pygame.K_LEFT]:
            self.x -= 5
        if keys[pygame.K_RIGHT]:
            self.x += 5

        self.y -= self.speed

    def draw(self, surface):
        rect = pygame.Rect(
            self.x - self.w // 2,
            self.y - self.h // 2,
            self.w,
            self.h
        )
        pygame.draw.rect(surface, GREEN, rect)


# ================== AI 车 ==================
class EnemyCar:
    def __init__(self):
        self.x = random.randint(120, WIDTH - 120)
        self.y = -100
        self.speed = random.randint(4, 7)

    def update(self):
        self.y += self.speed

    def draw(self, surface):
        rect = pygame.Rect(self.x - 30, self.y - 50, 40, 70)
        pygame.draw.rect(surface, RED, rect)


# ================== UI ==================
def draw_menu():
    screen.fill(GRAY)
    t1 = font.render("2D 赛车游戏", True, WHITE)
    t2 = font.render("按 SPACE 开始游戏", True, GREEN)
    screen.blit(t1, (WIDTH // 2 - 100, 200))
    screen.blit(t2, (WIDTH // 2 - 140, 280))


def draw_game(player, enemies, score):
    screen.fill(GRAY)

    # 道路
    pygame.draw.rect(screen, WHITE, (60, 0, 20, HEIGHT))
    pygame.draw.rect(screen, WHITE, (WIDTH - 80, 0, 20, HEIGHT))

    player.draw(screen)
    for e in enemies:
        e.draw(screen)

    score_text = font.render(f"Score: {score}", True, WHITE)
    screen.blit(score_text, (20, 20))


def draw_game_over(score):
    screen.fill(BLACK)
    t1 = font.render("游戏结束", True, RED)
    t2 = font.render(f"最终分数: {score}", True, WHITE)
    t3 = font.render("按 R 重新开始", True, GREEN)
    screen.blit(t1, (WIDTH // 2 - 80, 200))
    screen.blit(t2, (WIDTH // 2 - 100, 260))
    screen.blit(t3, (WIDTH // 2 - 120, 330))


# ================== 主循环 ==================
def main():
    global state

    player = PlayerCar()
    enemies = []
    enemy_timer = 0
    score = 0

    while True:
        clock.tick(60)
        keys = pygame.key.get_pressed()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            if event.type == pygame.KEYDOWN:
                if state == MENU and event.key == pygame.K_SPACE:
                    state = PLAYING
                if state == GAME_OVER and event.key == pygame.K_r:
                    main()

        if state == MENU:
            draw_menu()

        elif state == PLAYING:
            player.update(keys)

            enemy_timer += 1
            if enemy_timer > 40:
                enemies.append(EnemyCar())
                enemy_timer = 0

            for e in enemies[:]:
                e.update()
                if e.y > HEIGHT + 100:
                    enemies.remove(e)
                    score += 1

            # 碰撞
            player_rect = pygame.Rect(
                player.x - player.w // 2,
                player.y - player.h // 2,
                player.w,
                player.h
            )

            for e in enemies:
                enemy_rect = pygame.Rect(e.x - 30, e.y - 50, 40, 70)
                if player_rect.colliderect(enemy_rect):
                    state = GAME_OVER

            draw_game(player, enemies, score)

        elif state == GAME_OVER:
            draw_game_over(score)

        pygame.display.flip()


if __name__ == "__main__":
    main()