# ===== CodeLab: Python 小游戏⑨:飞机大战(pygame) =====
# 来源: https://aoerliang.dpdns.org/articles/game-python-plane
# 以下代码片段按文章出现顺序拼接, 共 4 段

# ----- 片段 1 (python) -----
import pygame

W, H = 480, 640
plane = pygame.Rect(W // 2 - 25, H - 80, 50, 40)

def move_plane(keys):
    if keys[pygame.K_LEFT] and plane.left > 0:
        plane.move_ip(-6, 0)
    if keys[pygame.K_RIGHT] and plane.right < W:
        plane.move_ip(6, 0)
    if keys[pygame.K_UP] and plane.top > 0:
        plane.move_ip(0, -6)
    if keys[pygame.K_DOWN] and plane.bottom < H:
        plane.move_ip(0, 6)

# ----- 片段 2 (python) -----
bullets = []

def shoot(keys, now):
    global next_shot
    if keys[pygame.K_SPACE] and now >= next_shot:
        bullets.append(pygame.Rect(plane.centerx - 2, plane.top, 4, 12))
        next_shot = now + 200        # 200ms 一发

def update_bullets():
    for b in bullets[:]:
        b.move_ip(0, -10)
        if b.bottom < 0:
            bullets.remove(b)

# ----- 片段 3 (python) -----
enemies = []
lives = 3
score = 0

def spawn_enemy(now):
    if now >= next_spawn:
        enemies.append(pygame.Rect(random.randrange(W - 40), -40, 40, 30))
        next_spawn = now + 900

def update_enemies():
    global lives, score
    for e in enemies[:]:
        e.move_ip(0, 4)
        if e.top > H:
            enemies.remove(e); lives -= 1
            continue
        for b in bullets[:]:
            if e.colliderect(b):
                enemies.remove(e); bullets.remove(b)
                score += 10
                break
        if plane.colliderect(e):
            enemies.remove(e); lives -= 1

# ----- 片段 4 (python) -----
import random, pygame

W, H = 480, 640
pygame.init()
screen = pygame.display.set_mode((W, H))
clock = pygame.time.Clock()
font = pygame.font.SysFont('simhei', 26)

plane = pygame.Rect(W // 2 - 25, H - 80, 50, 40)
bullets = []
enemies = []
lives = 3
score = 0
next_shot = 0
next_spawn = 0
game_over = False

while not game_over:
    now = pygame.time.get_ticks()
    keys = pygame.key.get_pressed()
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            pygame.quit(); raise SystemExit
    move_plane(keys)
    shoot(keys, now)
    update_bullets()
    spawn_enemy(now)
    update_enemies()
    if lives <= 0:
        game_over = True
        break

    screen.fill((10, 10, 25))
    pygame.draw.rect(screen, (90, 200, 255), plane, border_radius=8)
    for b in bullets:
        pygame.draw.rect(screen, (255, 220, 80), b)
    for e in enemies:
        pygame.draw.rect(screen, (230, 80, 80), e, border_radius=6)
    screen.blit(font.render('得分 %d  生命 %d' % (score, lives), True, (255, 255, 255)), (10, 10))
    pygame.display.flip()
    clock.tick(60)
print('游戏结束,最终得分:', score)
