import pygame
import sys
import os

# 初始化Pygame
pygame.init()

# 游戏设置
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 60

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
GRAY = (128, 128, 128)
BROWN = (139, 69, 19)
YELLOW = (255, 255, 0)
PURPLE = (128, 0, 128)
ORANGE = (255, 165, 0)

class Player:
    """玩家基类"""
    def __init__(self, x, y, color, name):
        self.x = x
        self.y = y
        self.width = 30
        self.height = 40
        self.color = color
        self.name = name
        self.vel_x = 0
        self.vel_y = 0
        self.speed = 5
        self.jump_power = -12
        self.gravity = 0.6
        self.on_ground = False
        self.lives = 3
        self.active = True
        
    def move(self, keys, left_key, right_key, jump_key, platforms, spikes, doors):
        """移动玩家"""
        # 水平移动
        self.vel_x = 0
        if keys[left_key]:
            self.vel_x = -self.speed
        if keys[right_key]:
            self.vel_x = self.speed
            
        # 跳跃
        if keys[jump_key] and self.on_ground:
            self.vel_y = self.jump_power
            self.on_ground = False
            
        # 应用重力
        self.vel_y += self.gravity
        if self.vel_y > 15:
            self.vel_y = 15
            
        # 水平碰撞检测
        self.x += self.vel_x
        self.check_collision(platforms, 'horizontal')
        
        # 垂直碰撞检测
        self.y += self.vel_y
        self.on_ground = False
        self.check_collision(platforms, 'vertical')
        
        # 检查边界
        if self.x < 0:
            self.x = 0
        if self.x > SCREEN_WIDTH - self.width:
            self.x = SCREEN_WIDTH - self.width
        if self.y > SCREEN_HEIGHT:
            self.die()
            
        # 检查尖刺
        self.check_spikes(spikes)
        
        # 检查门
        player_rect = self.get_rect()
        for door in doors:
            if player_rect.colliderect(door.rect):
                return door.color
        return None
        
    def check_collision(self, platforms, direction):
        """碰撞检测"""
        player_rect = self.get_rect()
        for platform in platforms:
            if player_rect.colliderect(platform.rect):
                if direction == 'horizontal':
                    if self.vel_x > 0:
                        self.x = platform.rect.left - self.width
                    elif self.vel_x < 0:
                        self.x = platform.rect.right
                elif direction == 'vertical':
                    if self.vel_y > 0:
                        self.y = platform.rect.top - self.height
                        self.on_ground = True
                        self.vel_y = 0
                    elif self.vel_y < 0:
                        self.y = platform.rect.bottom
                        self.vel_y = 0
                        
    def check_spikes(self, spikes):
        """检查尖刺碰撞"""
        player_rect = self.get_rect()
        for spike in spikes:
            if player_rect.colliderect(spike.rect):
                self.die()
                
    def die(self):
        """玩家死亡"""
        self.lives -= 1
        if self.lives <= 0:
            self.active = False
        else:
            # 重生
            if self.name == "火人":
                self.x = 100
                self.y = 500
            else:
                self.x = 650
                self.y = 500
            self.vel_x = 0
            self.vel_y = 0
            
    def get_rect(self):
        """返回玩家矩形"""
        return pygame.Rect(self.x, self.y, self.width, self.height)
        
    def draw(self, screen):
        """绘制玩家"""
        if self.active:
            pygame.draw.rect(screen, self.color, self.get_rect())
            # 绘制眼睛
            if self.name == "火人":
                pygame.draw.circle(screen, WHITE, (int(self.x + 8), int(self.y + 10)), 5)
                pygame.draw.circle(screen, WHITE, (int(self.x + 22), int(self.y + 10)), 5)
                pygame.draw.circle(screen, BLACK, (int(self.x + 10), int(self.y + 10)), 2)
                pygame.draw.circle(screen, BLACK, (int(self.x + 24), int(self.y + 10)), 2)
                # 火人特效 - 火焰
                pygame.draw.polygon(screen, ORANGE, [
                    (self.x + 5, self.y + 40),
                    (self.x + 15, self.y + 50),
                    (self.x + 25, self.y + 40)
                ])
            else:
                pygame.draw.circle(screen, WHITE, (int(self.x + 8), int(self.y + 10)), 5)
                pygame.draw.circle(screen, WHITE, (int(self.x + 22), int(self.y + 10)), 5)
                pygame.draw.circle(screen, BLACK, (int(self.x + 10), int(self.y + 10)), 2)
                pygame.draw.circle(screen, BLACK, (int(self.x + 24), int(self.y + 10)), 2)
                # 冰人特效 - 冰晶
                pygame.draw.polygon(screen, (173, 216, 230), [
                    (self.x + 15, self.y + 40),
                    (self.x + 5, self.y + 50),
                    (self.x + 25, self.y + 50)
                ])

class Platform:
    """平台类"""
    def __init__(self, x, y, width, height, color=GRAY):
        self.rect = pygame.Rect(x, y, width, height)
        self.color = color
        
    def draw(self, screen):
        pygame.draw.rect(screen, self.color, self.rect)
        pygame.draw.rect(screen, BLACK, self.rect, 2)

class Spike:
    """尖刺类"""
    def __init__(self, x, y):
        self.rect = pygame.Rect(x, y, 20, 20)
        
    def draw(self, screen):
        pygame.draw.polygon(screen, RED, [
            (self.rect.x, self.rect.y + self.rect.height),
            (self.rect.x + self.rect.width//2, self.rect.y),
            (self.rect.x + self.rect.width, self.rect.y + self.rect.height)
        ])

class Door:
    """门类"""
    def __init__(self, x, y, color):
        self.rect = pygame.Rect(x, y, 40, 60)
        self.color = color
        self.open = False
        
    def draw(self, screen):
        color = YELLOW if self.open else self.color
        pygame.draw.rect(screen, color, self.rect)
        pygame.draw.rect(screen, BLACK, self.rect, 3)
        if self.color == RED:
            pygame.draw.circle(screen, WHITE, (self.rect.x + 30, self.rect.y + 30), 5)
        else:
            pygame.draw.circle(screen, WHITE, (self.rect.x + 10, self.rect.y + 30), 5)

class Game:
    """游戏主类"""
    def __init__(self):
        self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        pygame.display.set_caption("森林冰火人")
        
        # 加载中文字体
        self.fonts = self.load_chinese_fonts()
        
        self.clock = pygame.time.Clock()
        self.running = True
        self.level_complete = False
        self.winner = None
        
        # 创建游戏元素
        self.create_level()
        
    def load_chinese_fonts(self):
        """加载中文字体"""
        fonts = {}
        font_sizes = {'small': 24, 'medium': 36, 'large': 72}
        
        # 尝试多种方法加载中文字体
        font_loaded = False
        
        # 方法1: 尝试从系统字体目录加载
        system_fonts = []
        if sys.platform == 'win32':
            # Windows系统字体目录
            font_dirs = [
                'C:/Windows/Fonts/',
                os.path.expanduser('~/AppData/Local/Microsoft/Windows/Fonts/')
            ]
            system_fonts = [
                'simhei.ttf', 'msyh.ttc', 'msyhbd.ttc', 
                'simsun.ttc', 'STKAITI.TTF', 'STZHONGS.TTF',
                'FZSTK.TTF', 'FZXHJK.TTF', 'YouYuan.ttf'
            ]
        elif sys.platform == 'darwin':
            # macOS系统字体目录
            font_dirs = ['/System/Library/Fonts/', '/Library/Fonts/']
            system_fonts = [
                'PingFang.ttc', 'STHeiti Light.ttc', 
                'STSong.ttf', 'STKaiti.ttf'
            ]
        else:
            # Linux系统字体目录
            font_dirs = [
                '/usr/share/fonts/truetype/',
                '/usr/local/share/fonts/'
            ]
            system_fonts = [
                'wqy-microhei.ttc', 'wqy-zenhei.ttc',
                'NotoSansCJK-Regular.ttc'
            ]
        
        # 尝试加载系统字体
        for font_dir in font_dirs:
            if not os.path.exists(font_dir):
                continue
            for font_name in system_fonts:
                font_path = os.path.join(font_dir, font_name)
                if os.path.exists(font_path):
                    try:
                        for size_name, size in font_sizes.items():
                            fonts[size_name] = pygame.font.Font(font_path, size)
                        font_loaded = True
                        print(f"成功加载中文字体: {font_path}")
                        return fonts
                    except:
                        continue
        
        # 方法2: 尝试从当前目录加载
        local_fonts = ['simhei.ttf', 'msyh.ttc', 'font.ttf']
        for font_name in local_fonts:
            if os.path.exists(font_name):
                try:
                    for size_name, size in font_sizes.items():
                        fonts[size_name] = pygame.font.Font(font_name, size)
                    font_loaded = True
                    print(f"成功加载本地中文字体: {font_name}")
                    return fonts
                except:
                    continue
        
        # 方法3: 创建自带中文字符的图片文字（备用方案）
        if not font_loaded:
            print("未找到中文字体，使用默认字体（中文可能显示为方框）")
            for size_name, size in font_sizes.items():
                fonts[size_name] = pygame.font.Font(None, size)
        
        return fonts
        
    def create_level(self):
        """创建关卡"""
        self.platforms = [
            Platform(0, 550, 800, 50, GRAY),
            Platform(100, 450, 150, 20, BROWN),
            Platform(350, 450, 150, 20, BROWN),
            Platform(600, 450, 150, 20, BROWN),
            Platform(200, 350, 100, 20, BROWN),
            Platform(500, 350, 100, 20, BROWN),
            Platform(350, 250, 100, 20, BROWN),
            Platform(50, 200, 80, 20, BROWN),
            Platform(670, 200, 80, 20, BROWN),
            # 新增移动平台（静态版本）
            Platform(300, 150, 200, 20, GREEN),
        ]
        
        self.spikes = [
            Spike(180, 530),
            Spike(400, 530),
            Spike(620, 530),
            Spike(80, 480),
            Spike(700, 480),
            Spike(350, 130),  # 新增尖刺
        ]
        
        self.doors = [
            Door(50, 490, RED),
            Door(710, 490, BLUE),
        ]
        
        self.fireboy = Player(100, 500, RED, "火人")
        self.watergirl = Player(650, 500, BLUE, "冰人")
        
        self.level_complete = False
        self.winner = None
        
    def handle_events(self):
        """处理事件"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    self.create_level()
                if event.key == pygame.K_ESCAPE:
                    self.running = False
                    
    def update(self):
        """更新游戏状态"""
        if self.level_complete:
            return
            
        keys = pygame.key.get_pressed()
        
        fire_door = self.fireboy.move(
            keys, pygame.K_a, pygame.K_d, pygame.K_w,
            self.platforms, self.spikes, self.doors
        )
        
        water_door = self.watergirl.move(
            keys, pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP,
            self.platforms, self.spikes, self.doors
        )
        
        if fire_door == RED and self.fireboy.active:
            self.level_complete = True
            self.winner = "火人"
            self.doors[0].open = True
        elif water_door == BLUE and self.watergirl.active:
            self.level_complete = True
            self.winner = "冰人"
            self.doors[1].open = True
            
        if not self.fireboy.active or not self.watergirl.active:
            self.level_complete = True
            self.winner = None
            
    def draw_chinese_text(self, text, font_key, color, x, y, center=False):
        """绘制中文文本"""
        try:
            font = self.fonts[font_key]
            surface = font.render(text, True, color)
            if center:
                rect = surface.get_rect(center=(x, y))
                self.screen.blit(surface, rect)
            else:
                self.screen.blit(surface, (x, y))
        except Exception as e:
            # 如果渲染失败，使用方框占位
            print(f"文字渲染失败: {text}, 错误: {e}")
            # 绘制一个彩色方块作为占位
            pygame.draw.rect(self.screen, color, (x, y, len(text)*15, 30), 2)
        
    def draw(self):
        """绘制游戏画面"""
        self.screen.fill(WHITE)
        
        # 绘制装饰性背景
        for i in range(0, SCREEN_WIDTH, 50):
            pygame.draw.line(self.screen, (200, 200, 200), (i, 0), (i, SCREEN_HEIGHT), 1)
        for i in range(0, SCREEN_HEIGHT, 50):
            pygame.draw.line(self.screen, (200, 200, 200), (0, i), (SCREEN_WIDTH, i), 1)
        
        # 绘制平台
        for platform in self.platforms:
            platform.draw(self.screen)
            
        # 绘制尖刺
        for spike in self.spikes:
            spike.draw(self.screen)
            
        # 绘制门
        for door in self.doors:
            door.draw(self.screen)
            
        # 绘制玩家
        self.fireboy.draw(self.screen)
        self.watergirl.draw(self.screen)
        
        # 显示中文信息
        # 火人生命值
        fire_text = f"火人: {self.fireboy.lives}"
        self.draw_chinese_text(fire_text, 'small', RED, 10, 10)
        
        # 冰人生命值
        water_text = f"冰人: {self.watergirl.lives}"
        self.draw_chinese_text(water_text, 'small', BLUE, 10, 40)
        
        # 显示控制提示
        controls = "WASD: 火人 | 方向键: 冰人 | R: 重新开始 | ESC: 退出"
        self.draw_chinese_text(controls, 'small', BLACK, 200, 10)
        
        # 显示关卡提示
        hint = "🔥 火人进红门 | 💧 冰人进蓝门"
        self.draw_chinese_text(hint, 'small', PURPLE, 200, 40)
        
        # 显示游戏结束信息
        if self.level_complete:
            overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
            overlay.set_alpha(180)
            overlay.fill((200, 200, 200))
            self.screen.blit(overlay, (0, 0))
            
            if self.winner:
                # 胜利信息
                text = f"🏆 {self.winner} 胜利！"
                self.draw_chinese_text(text, 'large', (0, 200, 0), 
                                     SCREEN_WIDTH//2, SCREEN_HEIGHT//2 - 30, center=True)
                
                restart_text = "按 R 重新开始"
                self.draw_chinese_text(restart_text, 'medium', BLACK, 
                                     SCREEN_WIDTH//2, SCREEN_HEIGHT//2 + 30, center=True)
            else:
                text = "💀 游戏结束！"
                self.draw_chinese_text(text, 'large', RED, 
                                     SCREEN_WIDTH//2, SCREEN_HEIGHT//2 - 30, center=True)
                
                restart_text = "按 R 重新开始"
                self.draw_chinese_text(restart_text, 'medium', BLACK, 
                                     SCREEN_WIDTH//2, SCREEN_HEIGHT//2 + 30, center=True)
            
        pygame.display.flip()
        
    def run(self):
        """游戏主循环"""
        while self.running:
            self.handle_events()
            self.update()
            self.draw()
            self.clock.tick(FPS)
            
        pygame.quit()
        sys.exit()

if __name__ == "__main__":
    game = Game()
    game.run()