import pygame
import random
import sys
import os

pygame.init()

# 窗口参数
WIDTH, HEIGHT = 600, 800
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("仙鹤云游 · 躲避")
clock = pygame.time.Clock()
FPS = 60

# 国风配色
BG_TOP = (15, 28, 45)
BG_BOTTOM = (30, 55, 75)
WHITE_CRANE = (254, 254, 254)
WING_GREY = (220, 220, 220)
HEAD_RED = (220, 25, 25)
BEAK_YELLOW = (235, 210, 80)
STONE_COLOR = (86, 78, 68)
CLOUD_COLOR = (180, 188, 195)
RED = (168, 36, 36)
GOLD = (218, 170, 96)

# 字体兼容函数，适配海龟编辑器
def get_font(size):
    try:
        return pygame.font.SysFont("simhei", size)
    except Exception:
        try:
            return pygame.font.SysFont("sans-serif", size)
        except:
            font_path = os.path.join(pygame.__path__[0], 'freesansbold.ttf')
            return pygame.font.Font(font_path, size)


font_big = get_font(65)
font_mid = get_font(36)
font_small = get_font(24)


def draw_gradient_bg():
    """水墨渐变古风天空背景"""
    for y in range(HEIGHT):
        ratio = y / HEIGHT
        r = int(BG_TOP[0] * (1 - ratio) + BG_BOTTOM[0] * ratio)
        g = int(BG_TOP[1] * (1 - ratio) + BG_BOTTOM[1] * ratio)
        b = int(BG_TOP[2] * (1 - ratio) + BG_BOTTOM[2] * ratio)
        pygame.draw.line(screen, (r, g, b), (0, y), (WIDTH, y))


class Crane(pygame.sprite.Sprite):
    # 精致国风仙鹤
    def __init__(self):
        super().__init__()
        self.width, self.height = 55, 75
        self.image = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
        # 身体
        pygame.draw.ellipse(self.image, WHITE_CRANE, [18, 30, 32, 38])
        # 长长的脖子
        pygame.draw.line(self.image, WHITE_CRANE, (34, 30), (42, 12), 6)
        # 头部
        pygame.draw.circle(self.image, WHITE_CRANE, (44, 10), 9)
        # 丹顶红冠
        pygame.draw.circle(self.image, HEAD_RED, (44, 6), 4)
        # 喙
        pygame.draw.polygon(self.image, BEAK_YELLOW, [(52, 10), (62, 13), (52, 16)])
        # 眼睛黑点
        pygame.draw.circle(self.image, (0, 0, 0), (47, 11), 2)
        # 左翼
        pygame.draw.ellipse(self.image, WING_GREY, [2, 32, 22, 28])
        # 右翼
        pygame.draw.ellipse(self.image, WING_GREY, [38, 33, 16, 26])
        # 长尾羽毛
        pygame.draw.polygon(self.image, WHITE_CRANE, [(22, 66), (16, 74), (36, 74), (30, 66)])

        self.rect = self.image.get_rect()
        self.rect.centerx = WIDTH // 2
        self.rect.bottom = HEIGHT - 40
        self.speed = 7

    def update(self):
        vx, vy = 0, 0
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            vx = -self.speed
        if keys[pygame.K_RIGHT]:
            vx = self.speed
        if keys[pygame.K_UP]:
            vy = -self.speed
        if keys[pygame.K_DOWN]:
            vy = self.speed
        self.rect.x += vx
        self.rect.y += vy
        # 屏幕边界锁住
        self.rect.left = max(0, self.rect.left)
        self.rect.right = min(WIDTH, self.rect.right)
        self.rect.top = max(0, self.rect.top)
        self.rect.bottom = min(HEIGHT, self.rect.bottom)


class WindObstacle(pygame.sprite.Sprite):
    # 障碍物：山石 / 乌云
    def __init__(self, level):
        super().__init__()
        self.kind = random.choice(["stone", "cloud"])
        w = random.randint(45, 90)
        h = random.randint(45, 90)
        self.image = pygame.Surface((w, h), pygame.SRCALPHA)
        if self.kind == "stone":
            pygame.draw.polygon(self.image, STONE_COLOR,
                                [(w * 0.5, 0), (w, h * 0.6), (w * 0.7, h), (w * 0.3, h), (0, h * 0.5)])
        else:
            pygame.draw.ellipse(self.image, CLOUD_COLOR, [0, 0, w, h])
        self.rect = self.image.get_rect()
        self.rect.x = random.randint(0, WIDTH - w)
        self.rect.y = random.randint(-100, -20)
        self.speed = 4 + level * 0.7

    def update(self):
        self.rect.y += self.speed
        if self.rect.top > HEIGHT:
            self.kill()


def draw_text(text, font, color, cx, cy):
    surf = font.render(text, True, color)
    r = surf.get_rect(center=(cx, cy))
    screen.blit(surf, r)


def game():
    all_sp = pygame.sprite.Group()
    obs_group = pygame.sprite.Group()
    crane = Crane()
    all_sp.add(crane)

    score = 0
    spawn_timer = 0
    gameover = False

    while True:
        clock.tick(FPS)
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if gameover and e.type == pygame.KEYDOWN:
                if e.key == pygame.K_SPACE:
                    game()
                    return

        if not gameover:
            all_sp.update()
            difficulty = int(score / 8)
            spawn_timer += 1
            spawn_rate = max(22, 45 - difficulty * 4)
            if spawn_timer > spawn_rate:
                new_obs = WindObstacle(difficulty)
                all_sp.add(new_obs)
                obs_group.add(new_obs)
                spawn_timer = 0
                score += 1
            if pygame.sprite.spritecollide(crane, obs_group, False):
                gameover = True

        draw_gradient_bg()
        all_sp.draw(screen)
        draw_text(f"分数：{score}", font_mid, GOLD, 70, 32)

        if gameover:
            draw_text("仙鹤遇险", font_big, RED, WIDTH // 2, HEIGHT // 2 - 60)
            draw_text("按下空格重新云游", font_small, GOLD, WIDTH // 2, HEIGHT // 2 + 20)

        pygame.display.flip()


if __name__ == "__main__":
    game() 