以下是一个简单的飞机大战游戏的Python代码示例:
import pygame
import random
# 初始化pygame
pygame.init()
# 设置屏幕大小和标题
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("飞机大战")
# 设置颜色
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 定义飞机类
class Plane(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface([50, 30])
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.x = screen_width // 2
self.rect.y = screen_height - 40
self.change_x = 0
def update(self):
self.rect.x += self.change_x
if self.rect.x < 0:
self.rect.x = 0
if self.rect.x > screen_width - 50:
self.rect.x = screen_width - 50
def go_left(self):
self.change_x = -5
def go_right(self):
self.change_x = 5
def stop(self):
self.change_x = 0
# 定义敌人类
class Enemy(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface([40, 25])
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.x = random.randint(0, screen_width - 40)
self.rect.y = -40
self.speed = random.randint(1, 3)
def update(self):
self.rect.y += self.speed
if self.rect.y > screen_height:
self.rect.y = -40
self.rect.x = random.randint(0, screen_width - 40)
self.speed = random.randint(1, 3)
# 初始化敌机精灵组和飞机精灵组
all_sprites = pygame.sprite.Group()
plane = Plane()
all_sprites.add(plane)
enemies = pygame.sprite.Group()
for i in range(5):
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 = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
plane.go_left()
elif event.key == pygame.K_RIGHT:
plane.go_right()
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
plane.stop()
elif event.key == pygame.K_SPACE: # 发射子弹,这里需要自己实现子弹类和逻辑,这里省略了子弹类的定义和逻辑实现。