import pygame
import random
import sys
import os

# 初始化pygame
pygame.init()

# 窗口设置
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 700
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("飞行躲避小游戏")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 120, 255)
GRAY = (80, 80, 80)

# 时钟
clock = pygame.time.Clock()
FPS = 60

# ==========修复字体BUG==========
# 放弃SysFont，使用内置默认字体，规避海龟编辑器sysfont底层报错
try:
    # 优先加载系统黑体
    font = pygame.font.Font("simhei.ttf", 36)
    small_font = pygame.font.Font("simhei.ttf",24)
except Exception:
    # 终极兼容方案，使用pygame默认内置字体对象，不传None
    font = pygame.font.Font(None, 36)
    small_font = pygame.font.Font(None,24)


class Plane:
    def __init__(self):
        self.width = 40
        self.height = 60
        self.x = SCREEN_WIDTH//2 - self.width//2
        self.y = SCREEN_HEIGHT - 100
        self.speed = 6
        self.rect = pygame.Rect(self.x,self.y,self.width,self.height)

    def update(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] and self.rect.left>0:
            self.rect.x -= self.speed
        if keys[pygame.K_RIGHT] and self.rect.right<SCREEN_WIDTH:
            self.rect.x += self.speed
        if keys[pygame.K_UP] and self.rect.top>0:
            self.rect.y -= self.speed
        if keys[pygame.K_DOWN] and self.rect.bottom<SCREEN_HEIGHT:
            self.rect.y += self.speed

    def draw(self):
        pygame.draw.polygon(screen,BLUE,[
            (self.rect.centerx, self.rect.top),
            (self.rect.left, self.rect.bottom),
            (self.rect.right, self.rect.bottom)
        ])


class Obstacle:
    def __init__(self):
        self.w = random.randint(60,120)
        self.h = 30
        self.x = random.randint(0, SCREEN_WIDTH-self.w)
        self.y = -self.h
        self.speed = random.randint(4,7)
        self.rect = pygame.Rect(self.x,self.y,self.w,self.h)

    def update(self):
        self.rect.y += self.speed

    def draw(self):
        pygame.draw.rect(screen,RED,self.rect)


def draw_button(x,y,w,h,text):
    btn_rect = pygame.Rect(x,y,w,h)
    pygame.draw.rect(screen,GRAY,btn_rect)
    txt = font.render(text,True,WHITE)
    screen.blit(txt,(x+10,y+5))
    return btn_rect


def game_loop():
    plane = Plane()
    obstacle_list = []
    score = 0
    game_over = False

    while True:
        screen.fill(BLACK)
        clock.tick(FPS)

        # 事件监听
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            # 游戏结束点击重启按钮
            if game_over and event.type == pygame.MOUSEBUTTONDOWN:
                mx,my = pygame.mouse.get_pos()
                btn = draw_button(SCREEN_WIDTH//2-80, 400,160,50,"重新开始")
                if btn.collidepoint(mx,my):
                    return

        if not game_over:
            plane.update()
            # 生成障碍物
            if random.randint(1,30)==1:
                obstacle_list.append(Obstacle())

            for obs in obstacle_list[:]:
                obs.update()
                obs.draw()
                # 超出屏幕加分+删除
                if obs.rect.top>SCREEN_HEIGHT:
                    obstacle_list.remove(obs)
                    score += 1
                # 碰撞检测
                if obs.rect.colliderect(plane.rect):
                    game_over = True

            plane.draw()
            # 绘制分数
            score_text = small_font.render(f"分数:{score}",True,WHITE)
            screen.blit(score_text,(10,10))

        else:
            over_text = font.render("游戏结束!",True,RED)
            screen.blit(over_text,(SCREEN_WIDTH//2-110,250))
            score_text = font.render(f"最终分数:{score}",True,WHITE)
            screen.blit(score_text,(SCREEN_WIDTH//2-130,320))
            draw_button(SCREEN_WIDTH//2-80,400,160,50,"重新开始")

        pygame.display.flip()


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