import pygame
import random
import os

# ===================== 窗口基础设置 =====================
WIDTH = 800
HEIGHT = 960
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("飞机大战")
clock = pygame.time.Clock()
FPS = 60
# 改用系统黑体，完美显示中文，不会乱码空格
font = pygame.font.SysFont("simhei", 36)

# ========== 全局路径配置 ==========
img_path = "feiji"
sound_path = os.path.join("res", "sound")

def get_img(name):
    return os.path.join(img_path, name)
def get_sound(name):
    return os.path.join(sound_path, name)

# ===================== 加载图片（匹配feiji内素材） =====================
# 背景
bg = pygame.image.load(get_img("background.png")).convert()
bg = pygame.transform.scale(bg, (WIDTH, HEIGHT))

# 玩家飞机
me1 = pygame.image.load(get_img("hero1.png")).convert_alpha()
me1 = pygame.transform.scale(me1, (80, 70))
me2 = pygame.image.load(get_img("hero2.png")).convert_alpha()
me2 = pygame.transform.scale(me2, (80, 70))
# 玩家爆炸图
me_destroy = [
    pygame.transform.scale(pygame.image.load(get_img("hero_blowup_n1.png")).convert_alpha(), (80,70)),
    pygame.transform.scale(pygame.image.load(get_img("hero_blowup_n4.png")).convert_alpha(), (80,70)),
]

# 子弹
bullet1 = pygame.image.load(get_img("bullet1.png")).convert_alpha()
bullet1 = pygame.transform.scale(bullet1, (6,12))
bullet2 = pygame.image.load(get_img("bullet1.png")).convert_alpha()
bullet2 = pygame.transform.scale(bullet2, (6,12))

# 敌机
enemy1 = pygame.image.load(get_img("enemy0.png")).convert_alpha()
enemy1 = pygame.transform.scale(enemy1, (45,45))
enemy1_down = [
    pygame.transform.scale(pygame.image.load(get_img("enemy0_down1.png")).convert_alpha(), (45,45)),
    pygame.transform.scale(pygame.image.load(get_img("enemy0_down2.png")).convert_alpha(), (45,45)),
    pygame.transform.scale(pygame.image.load(get_img("enemy0_down3.png")).convert_alpha(), (45,45)),
    pygame.transform.scale(pygame.image.load(get_img("enemy0_down4.png")).convert_alpha(), (45,45)),
]

# ===================== 加载音效（res/sound配音保留） =====================
# 背景音乐
bg_music = pygame.mixer.Sound(get_sound("game_music.wav"))
bg_music.set_volume(0.3)
bg_music.play(-1)

# 各类音效
sound_bullet = pygame.mixer.Sound(get_sound("bullet.wav"))
sound_enemy_down = pygame.mixer.Sound(get_sound("enemy1_down.wav"))
sound_me_down = pygame.mixer.Sound(get_sound("me_down.wav"))
sound_use_bomb = pygame.mixer.Sound(get_sound("use_bomb.wav"))

# 无素材功能屏蔽
enemy2_list = []
enemy3_list = []
bomb_supply = None
bullet_supply = None
life = None
supplies = []
pause_img = None
resume_img = None
pause_rect = pygame.Rect(0,0,0,0)

# ===================== 游戏变量初始化 =====================
me_rect = me1.get_rect()
me_rect.centerx = WIDTH // 2
me_rect.bottom = HEIGHT - 30
me_speed = 8
me_life = 3
me_blink = False
blink_time = 0
is_double_bullet = False
bullet_timer = 0

bullets = []
bullet_speed = 12
enemy1_list = []
enemy_timer = 0
enemy1_boom = []
enemy2_boom = []
enemy3_boom = []

supply_timer = 0
score = 0
game_pause = False
game_over = False
bomb_count = 1

# ===================== 工具函数 =====================
def create_bullet():
    sound_bullet.play()
    if is_double_bullet:
        b1 = bullet1.get_rect()
        b1.centerx = me_rect.centerx - 20
        b1.bottom = me_rect.top
        b2 = bullet2.get_rect()
        b2.centerx = me_rect.centerx + 20
        b2.bottom = me_rect.top
        bullets.append([b1, "single"])
        bullets.append([b2, "double"])
    else:
        b = bullet1.get_rect()
        b.centerx = me_rect.centerx
        b.bottom = me_rect.top
        bullets.append([b, "single"])

def create_enemy():
    e = enemy1.get_rect()
    e.x = random.randint(0, WIDTH - e.width)
    e.bottom = random.randint(-120, -20)
    enemy1_list.append([e, random.randint(3, 6)])

def clear_all_enemy():
    global score
    sound_use_bomb.play()
    for e in enemy1_list:
        enemy1_boom.append([e[0], 0])
        score += 100
    enemy1_list.clear()

# ===================== 主游戏循环 =====================
running = True
while running:
    screen.blit(bg, (0, 0))
    time_passed = clock.tick(FPS)
    global_time = pygame.time.get_ticks()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and bomb_count > 0 and not game_pause and not game_over:
            bomb_count -= 1
            clear_all_enemy()

    if game_pause:
        score_text = font.render(f"分数：{score}", True, (255, 255, 255))
        screen.blit(score_text, (20, 20))
        pygame.display.update()
        continue

    if game_over:
        bg_music.stop()
        over_text = font.render("游戏结束！关闭窗口退出", True, (255, 0, 0))
        screen.blit(over_text, (WIDTH//2 - 220, HEIGHT//2))
        pygame.display.update()
        continue

    # 玩家移动
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and me_rect.left > 0:
        me_rect.x -= me_speed
    if keys[pygame.K_RIGHT] and me_rect.right < WIDTH:
        me_rect.x += me_speed
    if keys[pygame.K_UP] and me_rect.top > 0:
        me_rect.y -= me_speed
    if keys[pygame.K_DOWN] and me_rect.bottom < HEIGHT:
        me_rect.y += me_speed

    # 玩家闪烁无敌
    if me_blink:
        blink_time += time_passed
        if blink_time > 1500:
            me_blink = False
            blink_time = 0
        if global_time // 100 % 2 == 0:
            screen.blit(me1, me_rect)
    else:
        if global_time // 120 % 2 == 0:
            screen.blit(me1, me_rect)
        else:
            screen.blit(me2, me_rect)

    # 自动生成子弹
    bullet_timer += time_passed
    if bullet_timer > 150:
        create_bullet()
        bullet_timer = 0

    # 子弹刷新
    for b in bullets[:]:
        b[0].y -= bullet_speed
        if b[0].bottom < 0:
            bullets.remove(b)
        else:
            screen.blit(bullet1, b[0])

    # 生成敌机
    enemy_timer += time_passed
    if enemy_timer > 400:
        create_enemy()
        enemy_timer = 0

    # 敌机逻辑
    for e in enemy1_list[:]:
        e[0].y += e[1]
        if e[0].top > HEIGHT:
            enemy1_list.remove(e)
        else:
            screen.blit(enemy1, e[0])
            # 子弹击中敌机
            for b in bullets[:]:
                if e[0].colliderect(b[0]):
                    sound_enemy_down.play()
                    enemy1_boom.append([e[0], 0])
                    enemy1_list.remove(e)
                    bullets.remove(b)
                    score += 100
                    break
            # 敌机撞玩家
            if e[0].colliderect(me_rect) and not me_blink:
                sound_me_down.play()
                me_life -= 1
                me_blink = True
                enemy1_boom.append([e[0], 0])
                enemy1_list.remove(e)
                if me_life <= 0:
                    game_over = True

    # 敌机爆炸动画
    for boom in enemy1_boom[:]:
        frame_idx = int(boom[1])
        if frame_idx < len(enemy1_down):
            screen.blit(enemy1_down[frame_idx], boom[0])
        boom[1] += 1
        if boom[1] >= len(enemy1_down):
            enemy1_boom.remove(boom)

    # UI中文文字（不再乱码）
    score_text = font.render(f"分数：{score}", True, (255, 255, 255))
    screen.blit(score_text, (20, 20))
    life_text = font.render(f"生命：{me_life}", True, (255, 255, 255))
    screen.blit(life_text, (20, 60))
    bomb_text = font.render(f"炸弹：{bomb_count}", True, (20, 20, 200))
    screen.blit(bomb_text, (20, 100))

    pygame.display.update()

pygame.quit()