import pygame
import random
import sys
import os

# 初始化
pygame.init()

WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("骑老奶奶过马路 🧓🏃")

# 颜色...
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (100, 100, 100)
DARK_GRAY = (50, 50, 50)
ROAD_COLOR = (60, 60, 60)
LINE_COLOR = (255, 255, 0)
GRASS_COLOR = (34, 139, 34)
SKIN_COLOR = (255, 218, 185)
HAIR_COLOR = (200, 200, 200)
SHIRT_COLOR = (0, 150, 200)

# 玩家参数
PLAYER_WIDTH = 40
PLAYER_HEIGHT = 60
PLAYER_SPEED = 5

# 车辆参数
CAR_WIDTH = 60
CAR_HEIGHT = 30
CAR_SPEED_MIN = 2
CAR_SPEED_MAX = 6
CAR_SPAWN_DELAY = 60

clock = pygame.time.Clock()

# ---------- 稳健的字体加载函数 ----------
def get_font(size):
    # 常见中文字体路径（按系统分类）
    font_paths = [
        "C:/Windows/Fonts/msyh.ttf",        # 微软雅黑（Win7+）
        "C:/Windows/Fonts/simsun.ttc",      # 宋体
        "C:/Windows/Fonts/simhei.ttf",      # 黑体
        "/System/Library/Fonts/PingFang.ttc", # macOS
        "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", # Linux
        "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
    ]
    for path in font_paths:
        if os.path.exists(path):
            try:
                return pygame.font.Font(path, size)
            except:
                continue
    # 都找不到就回退默认（可能无法显示中文，但不会崩溃）
    return pygame.font.Font(None, size)

font = get_font(48)  # 用于提示信息

# ---------- 玩家类 ----------
class Player:
    # ... 代码与之前完全相同（省略，保持不变）
    def __init__(self):
        self.x = WIDTH // 2 - PLAYER_WIDTH // 2
        self.y = HEIGHT - PLAYER_HEIGHT - 20
        self.width = PLAYER_WIDTH
        self.height = PLAYER_HEIGHT
        self.rect = pygame.Rect(self.x, self.y, self.width, self.height)

    def move(self, dx, dy):
        new_x = self.x + dx
        new_y = self.y + dy
        if 0 <= new_x <= WIDTH - self.width:
            self.x = new_x
        if new_y >= 0:
            self.y = new_y
        self.rect.topleft = (self.x, self.y)

    def draw(self, surface):
        body_rect = pygame.Rect(self.x + 5, self.y + 20, 30, 35)
        pygame.draw.ellipse(surface, (160, 100, 80), body_rect)
        head_center = (self.x + 20, self.y + 15)
        pygame.draw.circle(surface, SKIN_COLOR, head_center, 12)
        for offset in [(-10, -8), (-5, -12), (0, -14), (5, -12), (10, -8)]:
            pygame.draw.circle(surface, HAIR_COLOR, 
                               (head_center[0] + offset[0], head_center[1] + offset[1]), 4)
        pygame.draw.line(surface, (0, 0, 100), (self.x + 10, self.y + 55), (self.x + 10, self.y + 65), 4)
        pygame.draw.line(surface, (0, 0, 100), (self.x + 30, self.y + 55), (self.x + 30, self.y + 65), 4)

        rider_x = self.x + 15
        rider_y = self.y - 5
        pygame.draw.rect(surface, SHIRT_COLOR, (rider_x, rider_y, 10, 15))
        pygame.draw.circle(surface, SKIN_COLOR, (rider_x + 5, rider_y - 5), 7)
        pygame.draw.line(surface, SKIN_COLOR, (rider_x, rider_y + 2), (rider_x - 5, rider_y + 10), 3)
        pygame.draw.line(surface, SKIN_COLOR, (rider_x + 10, rider_y + 2), (rider_x + 15, rider_y + 10), 3)

# ---------- 车辆类 ----------
class Car:
    def __init__(self, x, y, speed, direction):
        self.x = x
        self.y = y
        self.width = CAR_WIDTH
        self.height = CAR_HEIGHT
        self.speed = speed
        self.direction = direction
        self.rect = pygame.Rect(x, y, self.width, self.height)
        self.color = (random.randint(50, 255), random.randint(50, 255), random.randint(50, 255))

    def update(self):
        self.x += self.speed * self.direction
        self.rect.x = self.x

    def draw(self, surface):
        pygame.draw.rect(surface, self.color, self.rect)
        window_color = (200, 230, 255)
        if self.direction == 1:
            pygame.draw.rect(surface, window_color, (self.x + 5, self.y + 5, 15, 10))
            pygame.draw.rect(surface, window_color, (self.x + 35, self.y + 5, 15, 10))
        else:
            pygame.draw.rect(surface, window_color, (self.x + 10, self.y + 5, 15, 10))
            pygame.draw.rect(surface, window_color, (self.x + 35, self.y + 5, 15, 10))

# ---------- 游戏循环 ----------
def game_loop():
    player = Player()
    cars = []
    frame_count = 0
    game_over = False
    win = False

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN and (game_over or win):
                if event.key == pygame.K_SPACE:
                    return  # 重开

        if not game_over and not win:
            keys = pygame.key.get_pressed()
            dx = dy = 0
            if keys[pygame.K_LEFT] or keys[pygame.K_a]:
                dx = -PLAYER_SPEED
            if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
                dx = PLAYER_SPEED
            if keys[pygame.K_UP] or keys[pygame.K_w]:
                dy = -PLAYER_SPEED
            if keys[pygame.K_DOWN] or keys[pygame.K_s]:
                dy = PLAYER_SPEED
            player.move(dx, dy)

        if not game_over and not win:
            frame_count += 1
            if frame_count % CAR_SPAWN_DELAY == 0:
                lane_y = random.choice([120, 200, 280, 360, 440])
                direction = random.choice([-1, 1])
                x = -CAR_WIDTH if direction == 1 else WIDTH
                speed = random.randint(CAR_SPEED_MIN, CAR_SPEED_MAX)
                cars.append(Car(x, lane_y, speed, direction))

        for car in cars:
            car.update()
        cars = [car for car in cars if -CAR_WIDTH < car.x < WIDTH + CAR_WIDTH]

        if not game_over and not win:
            for car in cars:
                if player.rect.colliderect(car.rect):
                    game_over = True
                    break
            if player.y <= 0:
                win = True

        # 绘制
        screen.fill(GRASS_COLOR)
        road_rect = pygame.Rect(0, 60, WIDTH, HEIGHT - 120)
        pygame.draw.rect(screen, ROAD_COLOR, road_rect)

        for y in range(100, HEIGHT - 80, 80):
            for x in range(0, WIDTH, 60):
                pygame.draw.rect(screen, LINE_COLOR, (x + 20, y, 30, 4))

        pygame.draw.rect(screen, DARK_GRAY, (0, 50, WIDTH, 10))
        pygame.draw.rect(screen, DARK_GRAY, (0, HEIGHT - 70, WIDTH, 10))

        for car in cars:
            car.draw(screen)
        player.draw(screen)

        # 显示信息
        if game_over:
            text = font.render("💥 游戏结束！按 空格键 重试", True, WHITE)
            screen.blit(text, text.get_rect(center=(WIDTH//2, 30)))
        elif win:
            text = font.render("🎉 恭喜过关！按 空格键 再来一次", True, WHITE)
            screen.blit(text, text.get_rect(center=(WIDTH//2, 30)))
        else:
            hint = font.render("↑↓←→ 移动", True, WHITE)
            screen.blit(hint, (10, 10))

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

if __name__ == "__main__":
    while True:
        game_loop()