import pygame
import sys
import math
import os

# 初始化 Pygame
pygame.init()

# 窗口设置
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("可操控火柴人 - WASD移动 | 空格跳跃")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GRAY = (200, 200, 200)

# 帧率控制
clock = pygame.time.Clock()
FPS = 60

# ----- 修复中文显示 -----
# 尝试加载系统中文字体，如果失败则使用默认字体并启用中文支持
def get_chinese_font(size):
    # 尝试常见的中文字体名称
    font_names = [
        "SimHei",           # 黑体 (Windows)
        "Microsoft YaHei",  # 微软雅黑 (Windows)
        "PingFang SC",      # 苹方 (macOS)
        "Noto Sans CJK SC", # 思源黑体 (Linux)
        "WenQuanYi Micro Hei", # 文泉驿微米黑 (Linux)
        "Arial Unicode MS", # 通用Unicode字体
    ]
    for name in font_names:
        try:
            font = pygame.font.SysFont(name, size)
            # 测试是否能渲染中文
            test_surface = font.render("测试", True, BLACK)
            return font
        except:
            continue
    # 如果都失败，使用默认字体并设置备用
    pygame.font.init()
    return pygame.font.Font(None, size)

# 创建中文字体对象
hint_font = get_chinese_font(24)
# ----- 修复结束 -----

# 火柴人参数
class Stickman:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.vx = 0
        self.vy = 0
        self.speed = 5
        self.jump_power = -12
        self.gravity = 0.6
        self.on_ground = False

        # 动画参数
        self.arm_angle = 0
        self.leg_angle = 0
        self.walk_cycle = 0
        self.is_moving = False

        # 面向方向: 1 右, -1 左
        self.facing = 1

        # 地面高度 (脚底位置)
        self.ground_y = HEIGHT - 100

    def update(self, keys):
        # 水平移动
        self.vx = 0
        if keys[pygame.K_a] or keys[pygame.K_LEFT]:
            self.vx = -self.speed
            self.facing = -1
        if keys[pygame.K_d] or keys[pygame.K_RIGHT]:
            self.vx = self.speed
            self.facing = 1

        # 跳跃
        if (keys[pygame.K_SPACE] or keys[pygame.K_w] or keys[pygame.K_UP]) and self.on_ground:
            self.vy = self.jump_power
            self.on_ground = False

        # 重力
        self.vy += self.gravity
        if self.vy > 15:
            self.vy = 15

        # 更新位置
        self.x += self.vx
        self.y += self.vy

        # 地面碰撞
        if self.y >= self.ground_y:
            self.y = self.ground_y
            self.vy = 0
            self.on_ground = True

        # 边界限制 (防止跑出屏幕)
        if self.x < 30:
            self.x = 30
        if self.x > WIDTH - 30:
            self.x = WIDTH - 30

        # 行走动画
        self.is_moving = abs(self.vx) > 0.5 and self.on_ground
        if self.is_moving:
            self.walk_cycle += 0.12
            if self.walk_cycle > 2 * math.pi:
                self.walk_cycle -= 2 * math.pi
            self.arm_angle = math.sin(self.walk_cycle) * 0.6
            self.leg_angle = math.sin(self.walk_cycle + math.pi) * 0.6
        else:
            # 静止时手臂和腿归位
            self.arm_angle *= 0.9
            self.leg_angle *= 0.9
            if abs(self.arm_angle) < 0.01:
                self.arm_angle = 0
            if abs(self.leg_angle) < 0.01:
                self.leg_angle = 0

    def draw(self, surface, mouse_pos):
        cx, cy = self.x, self.y

        # ----- 根据鼠标位置调整头部朝向 (眼睛) -----
        dx = mouse_pos[0] - cx
        dy = mouse_pos[1] - (cy - 60)
        angle_to_mouse = math.atan2(dy, dx)

        # 头 (圆形)
        head_radius = 20
        head_center = (cx, cy - 60)
        pygame.draw.circle(surface, BLACK, head_center, head_radius, 2)

        # 眼睛 - 朝向鼠标
        eye_distance = 8
        eye_offset = 6
        # 左眼 (从头部中心偏移)
        left_eye_angle = angle_to_mouse - 0.3
        right_eye_angle = angle_to_mouse + 0.3
        left_eye_x = head_center[0] + eye_distance * math.cos(left_eye_angle)
        left_eye_y = head_center[1] + eye_distance * math.sin(left_eye_angle)
        right_eye_x = head_center[0] + eye_distance * math.cos(right_eye_angle)
        right_eye_y = head_center[1] + eye_distance * math.sin(right_eye_angle)
        pygame.draw.circle(surface, RED, (int(left_eye_x), int(left_eye_y)), 3)
        pygame.draw.circle(surface, RED, (int(right_eye_x), int(right_eye_y)), 3)

        # 身体 (竖直线)
        body_top = (cx, cy - 40)
        body_bottom = (cx, cy + 20)
        pygame.draw.line(surface, BLACK, body_top, body_bottom, 3)

        # 肩膀位置
        shoulder_y = cy - 30

        # 手臂 (根据朝向和行走摆动)
        arm_len = 35
        # 左臂
        left_arm_angle = self.arm_angle if self.facing == 1 else -self.arm_angle
        left_arm_end = (
            cx - arm_len * math.cos(left_arm_angle),
            shoulder_y + arm_len * math.sin(left_arm_angle)
        )
        pygame.draw.line(surface, BLACK, (cx, shoulder_y), left_arm_end, 3)
        # 右臂 (与左臂反相)
        right_arm_angle = -self.arm_angle if self.facing == 1 else self.arm_angle
        right_arm_end = (
            cx + arm_len * math.cos(right_arm_angle),
            shoulder_y - arm_len * math.sin(right_arm_angle)
        )
        pygame.draw.line(surface, BLACK, (cx, shoulder_y), right_arm_end, 3)

        # 腿 (根据行走摆动)
        hip_y = cy + 20
        leg_len = 35
        # 左腿
        left_leg_angle = self.leg_angle if self.facing == 1 else -self.leg_angle
        left_leg_end = (
            cx - 25 * math.cos(left_leg_angle),
            hip_y + leg_len * math.sin(left_leg_angle)
        )
        pygame.draw.line(surface, BLACK, (cx, hip_y), left_leg_end, 3)
        # 右腿
        right_leg_angle = -self.leg_angle if self.facing == 1 else self.leg_angle
        right_leg_end = (
            cx + 25 * math.cos(right_leg_angle),
            hip_y - leg_len * math.sin(right_leg_angle)
        )
        pygame.draw.line(surface, BLACK, (cx, hip_y), right_leg_end, 3)

    def get_ground_y(self):
        return self.ground_y

# 创建火柴人
stickman = Stickman(WIDTH // 2, HEIGHT - 100)

# 主循环
running = True
while running:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 获取键盘和鼠标状态
    keys = pygame.key.get_pressed()
    mouse_pos = pygame.mouse.get_pos()

    # 更新火柴人
    stickman.update(keys)

    # 绘制
    screen.fill(WHITE)

    # 绘制地面参考线 (可选)
    ground_y = stickman.get_ground_y()
    pygame.draw.line(screen, GRAY, (0, ground_y + 5), (WIDTH, ground_y + 5), 2)

    stickman.draw(screen, mouse_pos)

    # 显示操作提示 (使用支持中文的字体)
    hint1 = hint_font.render("WASD / 方向键 移动", True, BLACK)
    hint2 = hint_font.render("空格 / W / 上键 跳跃", True, BLACK)
    hint3 = hint_font.render("鼠标控制视线方向", True, BLACK)
    screen.blit(hint1, (10, 10))
    screen.blit(hint2, (10, 40))
    screen.blit(hint3, (10, 70))

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

pygame.quit()
sys.exit()