import pygame
import sys
import random
import os

# 初始化Pygame
pygame.init()

# 屏幕尺寸
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_SIZE = (SCREEN_WIDTH, SCREEN_HEIGHT)

# 颜色定义 (RGB)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
PURPLE = (128, 0, 128)
GRAY = (100, 100, 100)
DARK_GRAY = (50, 50, 50)

# 游戏设置
FPS = 60
PLAYER_SIZE = 20
BULLET_SIZE = 6
PLAYER_SPEED = 5
BULLET_SPEED = 8
MAX_HP = 100
BULLET_DAMAGE = 20
SHOOT_COOLDOWN = 15  # 帧数间隔

# 初始化屏幕
screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption("像素枪战 - 双人对战")
clock = pygame.time.Clock()

# ========== 中文字体加载 ==========
def get_chinese_font(size):
    """获取支持中文的字体，按优先级尝试多个字体"""
    font_names = [
        "SimHei",
        "Microsoft YaHei",
        "SimSun",
        "KaiTi",
        "FangSong",
        "STHeiti",
        "STKaiti",
        "Noto Sans CJK SC",
        "PingFang SC",
        "WenQuanYi Micro Hei",
        "Arial Unicode MS",
    ]
    
    for name in font_names:
        try:
            font = pygame.font.SysFont(name, size)
            test_surface = font.render("测试", True, WHITE)
            if test_surface.get_width() > 0:
                print(f"使用字体: {name}")
                return font
        except:
            continue
    
    print("未找到中文字体，使用默认字体")
    return pygame.font.Font(None, size)

font_small = get_chinese_font(24)
font_medium = get_chinese_font(36)
font_large = get_chinese_font(48)


def show_text(surface, text, x, y, color=WHITE, font=font_small):
    """显示文本（支持中文）"""
    try:
        text_surface = font.render(text, True, color)
        surface.blit(text_surface, (x, y))
    except:
        text_surface = font.render("Text Error", True, color)
        surface.blit(text_surface, (x, y))


class Player:
    """玩家类"""
    def __init__(self, x, y, color, controls, name):
        self.rect = pygame.Rect(x, y, PLAYER_SIZE, PLAYER_SIZE)
        self.color = color
        self.hp = MAX_HP
        self.max_hp = MAX_HP
        self.direction = pygame.Vector2(0, -1)
        self.controls = controls
        self.shoot_timer = 0
        self.alive = True
        self.respawn_timer = 0
        self.name = name
        self.shoot_cooldown_frames = 0  # 射击冷却帧数

    def move(self, keys):
        """根据按键移动玩家"""
        dx, dy = 0, 0
        if keys[self.controls['up']]:
            dy -= PLAYER_SPEED
        if keys[self.controls['down']]:
            dy += PLAYER_SPEED
        if keys[self.controls['left']]:
            dx -= PLAYER_SPEED
        if keys[self.controls['right']]:
            dx += PLAYER_SPEED

        if dx != 0 or dy != 0:
            self.direction = pygame.Vector2(dx, dy).normalize()

        self.rect.x += dx
        self.rect.y += dy
        self.rect.clamp_ip(screen.get_rect())

    def shoot(self, bullets):
        """发射子弹"""
        if self.shoot_cooldown_frames <= 0 and self.alive:
            center = self.rect.center
            if self.direction.length() == 0:
                self.direction = pygame.Vector2(0, -1)
            # 子弹记录发射者
            bullet = Bullet(center[0], center[1], self.direction, self.color, self)
            bullets.append(bullet)
            self.shoot_cooldown_frames = SHOOT_COOLDOWN

    def update(self):
        """更新冷却和复活计时"""
        if self.shoot_cooldown_frames > 0:
            self.shoot_cooldown_frames -= 1
        
        if not self.alive:
            self.respawn_timer -= 1
            if self.respawn_timer <= 0:
                self.alive = True
                self.hp = self.max_hp
                self.rect.x = random.randint(50, SCREEN_WIDTH - 50 - PLAYER_SIZE)
                self.rect.y = random.randint(50, SCREEN_HEIGHT - 50 - PLAYER_SIZE)
                self.direction = pygame.Vector2(0, -1)

    def take_damage(self, damage):
        """受到伤害"""
        if self.alive:
            self.hp -= damage
            if self.hp <= 0:
                self.hp = 0
                self.alive = False
                self.respawn_timer = 90

    def draw(self, surface):
        """绘制玩家"""
        if not self.alive:
            pygame.draw.rect(surface, GRAY, self.rect, 2)
            if self.respawn_timer > 0:
                countdown_text = str(self.respawn_timer // 60 + 1)
                show_text(surface, countdown_text, self.rect.x + 4, self.rect.y - 25, GRAY, font_small)
            return
        
        pygame.draw.rect(surface, self.color, self.rect)
        pygame.draw.rect(surface, WHITE, (self.rect.x + 2, self.rect.y + 2, 4, 4))
        
        eye_offset = self.direction * 6
        eye_center = (self.rect.centerx + int(eye_offset.x), self.rect.centery + int(eye_offset.y))
        pygame.draw.circle(surface, WHITE, eye_center, 3)
        pygame.draw.circle(surface, BLACK, eye_center, 1)
        
        bar_width = self.rect.width
        bar_height = 4
        bar_x = self.rect.x
        bar_y = self.rect.y - 10
        hp_ratio = self.hp / self.max_hp
        pygame.draw.rect(surface, RED, (bar_x, bar_y, bar_width, bar_height))
        pygame.draw.rect(surface, GREEN, (bar_x, bar_y, int(bar_width * hp_ratio), bar_height))


class Bullet:
    """子弹类"""
    def __init__(self, x, y, direction, color, owner):
        self.rect = pygame.Rect(x - BULLET_SIZE//2, y - BULLET_SIZE//2, BULLET_SIZE, BULLET_SIZE)
        self.direction = direction.normalize()
        self.color = color
        self.speed = BULLET_SPEED
        self.owner = owner  # 记录发射者
        self.hit_timer = 5  # 无敌帧：刚发射的子弹不会立即击中自己

    def update(self):
        """更新位置"""
        self.rect.x += self.direction.x * self.speed
        self.rect.y += self.direction.y * self.speed
        if self.hit_timer > 0:
            self.hit_timer -= 1

    def draw(self, surface):
        """绘制子弹"""
        pygame.draw.rect(surface, WHITE, self.rect.inflate(4, 4), 1)
        pygame.draw.rect(surface, self.color, self.rect)


def main():
    # ========== 按键配置 ==========
    player1 = Player(100, 300, BLUE, {
        'up': pygame.K_w,
        'down': pygame.K_s,
        'left': pygame.K_a,
        'right': pygame.K_d,
        'shoot': pygame.K_LSHIFT
    }, "玩家1")
    
    player2 = Player(700, 300, RED, {
        'up': pygame.K_UP,
        'down': pygame.K_DOWN,
        'left': pygame.K_LEFT,
        'right': pygame.K_RIGHT,
        'shoot': pygame.K_RSHIFT
    }, "玩家2")

    players = [player1, player2]
    bullets = []
    
    running = True
    game_over = False
    winner = None

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r and game_over:
                    game_over = False
                    winner = None
                    for p in players:
                        p.alive = True
                        p.hp = p.max_hp
                        p.rect.x = random.randint(50, SCREEN_WIDTH - 50 - PLAYER_SIZE)
                        p.rect.y = random.randint(50, SCREEN_HEIGHT - 50 - PLAYER_SIZE)
                        p.direction = pygame.Vector2(0, -1)
                        p.shoot_cooldown_frames = 0
                    bullets.clear()

        keys = pygame.key.get_pressed()

        # 更新玩家
        for player in players:
            if player.alive:
                player.move(keys)
                if keys[player.controls['shoot']]:
                    player.shoot(bullets)
            player.update()

        # 更新子弹
        for bullet in bullets[:]:
            bullet.update()
            
            # 移除超出屏幕的子弹
            if not screen.get_rect().colliderect(bullet.rect):
                bullets.remove(bullet)
                continue
            
            # ========== 子弹碰撞检测（排除发射者自己） ==========
            for player in players:
                if player.alive and bullet.rect.colliderect(player.rect):
                    if player == bullet.owner:
                        continue  # 跳过自己的子弹
                    
                    player.take_damage(BULLET_DAMAGE)
                    if bullet in bullets:
                        bullets.remove(bullet)
                    break

        # 检测游戏结束
        alive_players = [p for p in players if p.alive]
        if len(alive_players) == 1 and not game_over:
            game_over = True
            winner = alive_players[0]
        elif len(alive_players) == 0 and not game_over:
            game_over = True
            winner = None

        # ========== 绘制 ==========
        screen.fill(DARK_GRAY)
        
        # 绘制网格
        for x in range(0, SCREEN_WIDTH, 40):
            pygame.draw.line(screen, GRAY, (x, 0), (x, SCREEN_HEIGHT), 1)
        for y in range(0, SCREEN_HEIGHT, 40):
            pygame.draw.line(screen, GRAY, (0, y), (SCREEN_WIDTH, y), 1)

        # 绘制子弹
        for bullet in bullets:
            bullet.draw(screen)

        # 绘制玩家
        for player in players:
            player.draw(screen)

        # ========== UI优化：HP显示在顶部两侧 ==========
        # 玩家1 HP - 左上角
        show_text(screen, f"玩家1 HP: {player1.hp}", 20, 15, BLUE, font_medium)
        
        # 玩家2 HP - 右上角（调整位置，确保不被遮挡）
        hp2_text = f"玩家2 HP: {player2.hp}"
        hp2_surface = font_medium.render(hp2_text, True, RED)
        hp2_rect = hp2_surface.get_rect()
        # 将右侧文字右对齐，距离右边缘20像素
        hp2_x = SCREEN_WIDTH - hp2_rect.width - 20
        screen.blit(hp2_surface, (hp2_x, 15))

        # 操作提示 - 底部
        show_text(screen, "WASD移动 | 左Shift射击", 20, SCREEN_HEIGHT - 40, BLUE, font_small)
        show_text(screen, "方向键移动 | 右Shift射击", SCREEN_WIDTH - 280, SCREEN_HEIGHT - 40, RED, font_small)
        
        # 游戏结束遮罩
        if game_over:
            overlay = pygame.Surface(SCREEN_SIZE, pygame.SRCALPHA)
            overlay.fill((0, 0, 0, 180))
            screen.blit(overlay, (0, 0))
            
            if winner:
                color = winner.color
                text = f"{winner.name} 获胜！"
            else:
                color = WHITE
                text = "平局！"
            
            text_surface = font_large.render(text, True, color)
            text_rect = text_surface.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2 - 30))
            screen.blit(text_surface, text_rect)
            
            restart_surface = font_medium.render("按 R 重新开始", True, WHITE)
            restart_rect = restart_surface.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2 + 30))
            screen.blit(restart_surface, restart_rect)

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

    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()