python">import pygame
import random
WINDOW_WIDTH = 600
WINDOW_HEIGHT = 800
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
pygame.init()
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("飞机大战")
clock = pygame.time.Clock()
class Plane(pygame.sprite.Sprite):def __init__(self):super().__init__()self.image = pygame.Surface([50, 50]) self.image.fill(WHITE)self.rect = self.image.get_rect()self.rect.x = WINDOW_WIDTH // 2self.rect.y = WINDOW_HEIGHT - 100self.speed = 5def update(self):keys = pygame.key.get_pressed()if keys[pygame.K_LEFT]:self.rect.x -= self.speedif keys[pygame.K_RIGHT]:self.rect.x += self.speedif self.rect.x < 0:self.rect.x = 0if self.rect.x > WINDOW_WIDTH - 50:self.rect.x = WINDOW_WIDTH - 50def shoot(self):bullet = Bullet(self.rect.x + 23, self.rect.y)all_sprites.add(bullet)bullets.add(bullet)
class Bullet(pygame.sprite.Sprite):def __init__(self, x, y):super().__init__()self.image = pygame.Surface([5, 10]) self.image.fill(WHITE)self.rect = self.image.get_rect()self.rect.x = xself.rect.y = yself.speed = 10def update(self):self.rect.y -= self.speedif self.rect.y < -10:self.kill()
class Enemy(pygame.sprite.Sprite):def __init__(self):super().__init__()self.image = pygame.Surface([30, 30]) self.image.fill(WHITE)self.rect = self.image.get_rect()self.rect.x = random.randint(0, WINDOW_WIDTH - 30)self.rect.y = 0self.speed = random.randint(1, 5)def update(self):self.rect.y += self.speedif self.rect.y > WINDOW_HEIGHT:self.rect.x = random.randint(0, WINDOW_WIDTH - 30)self.rect.y = 0self.speed = random.randint(1, 5)
all_sprites = pygame.sprite.Group()
player = Plane()
all_sprites.add(player)
bullets = pygame.sprite.Group()
enemies = pygame.sprite.Group()
for _ in range(10):enemy = Enemy()all_sprites.add(enemy)enemies.add(enemy)
running = True
while running:for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseelif event.type == pygame.KEYDOWN:if event.key == pygame.K_SPACE:player.shoot()all_sprites.update()if pygame.sprite.spritecollide(player, enemies, True):running = Falsefor bullet in bullets:pygame.sprite.spritecollide(bullet, enemies, True)window.fill(BLACK)all_sprites.draw(window)pygame.display.flip()clock.tick(60)
pygame.quit()