import pygame
import random

pygame.init()
W, H = 480, 600
screen = pygame.display.set_mode((W, H))
pygame.display.set_caption("飞行躲避")
clock = pygame.time.Clock()

# 颜色
BLACK = (0,0,0)
WHITE = (255,255,255)
BLUE = (30,144,255)
GRAY = (100,100,100)

# 玩家战机
plane_x = W//2 - 20
plane_y = H - 80
plane_w, plane_h = 40, 50
speed = 6

# 障碍物
blocks = []
block_w, block_h = 50, 40
block_speed = 4

score = 0
font = pygame.font.SysFont(None, 36)
run = True

while run:
    clock.tick(60)
    screen.fill(BLACK)

    # 事件处理
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            run = False

    # 按键移动
    key = pygame.key.get_pressed()
    if key[pygame.K_LEFT] and plane_x > 0:
        plane_x -= speed
    if key[pygame.K_RIGHT] and plane_x < W - plane_w:
        plane_x += speed
    if key[pygame.K_UP] and plane_y > 0:
        plane_y -= speed
    if key[pygame.K_DOWN] and plane_y < H - plane_h:
        plane_y += speed

    # 随机生成障碍物
    if random.randint(1,30) == 1:
        bx = random.randint(0, W-block_w)
        blocks.append([bx, -block_h])

    # 更新障碍物
    new_blocks = []
    for b in blocks:
        b[1] += block_speed
        if b[1] < H:
            new_blocks.append(b)
        else:
            score += 1
    blocks = new_blocks

    # 碰撞检测
    plane_rect = pygame.Rect(plane_x, plane_y, plane_w, plane_h)
    crash = False
    for b in blocks:
        b_rect = pygame.Rect(b[0], b[1], block_w, block_h)
        if plane_rect.colliderect(b_rect):
            crash = True
            break
    if crash:
        run = False

    # 绘制
    pygame.draw.rect(screen, BLUE, (plane_x, plane_y, plane_w, plane_h))
    for b in blocks:
        pygame.draw.rect(screen, GRAY, (b[0], b[1], block_w, block_h))

    # 显示分数
    text = font.render(f"分数：{score}", True, WHITE)
    screen.blit(text, (10,10))

    pygame.display.flip()

pygame.quit()