用Python写一个小飞机游戏程序
时间: 2023-03-22 12:01:40 浏览: 121
好的,以下是一个使用Python和Pygame库编写的小飞机游戏程序示例:
```python
import pygame
import random
# 初始化 Pygame 库
pygame.init()
# 定义游戏窗口的大小
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 800
SCREEN_SIZE = (SCREEN_WIDTH, SCREEN_HEIGHT)
# 设置窗口标题
pygame.display.set_caption("小飞机游戏")
# 创建游戏窗口
screen = pygame.display.set_mode(SCREEN_SIZE)
# 加载游戏图片资源
bg_img = pygame.image.load("images/background.png")
plane_img = pygame.image.load("images/plane.png")
bullet_img = pygame.image.load("images/bullet.png")
enemy_img = pygame.image.load("images/enemy.png")
# 定义游戏变量
score = 0
font = pygame.font.SysFont(None, 32)
# 定义游戏角色
class Plane(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = plane_img
self.rect = self.image.get_rect()
self.rect.centerx = SCREEN_WIDTH // 2
self.rect.bottom = SCREEN_HEIGHT - 20
self.speed = 5
self.bullets = pygame.sprite.Group()
def update(self):
key_pressed = pygame.key.get_pressed()
if key_pressed[pygame.K_LEFT]:
self.rect.x -= self.speed
if key_pressed[pygame.K_RIGHT]:
self.rect.x += self.speed
if key_pressed[pygame.K_SPACE]:
bullet = Bullet()
bullet.rect.centerx = self.rect.centerx
bullet.rect.top = self.rect.top
self.bullets.add(bullet)
# 控制飞机不飞出屏幕
if self.rect.left < 0:
self.rect.left = 0
elif self.rect.right > SCREEN_WIDTH:
self.rect.right = SCREEN_WIDTH
# 更新子弹
self.bullets.update()
def draw(self, surface):
surface.blit(self.image, self.rect)
self.bullets.draw(surface)
class Bullet(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = bullet_img
self.rect = self.image.get_rect()
self.speed = -10
def update(self):
self.rect.y += self.speed
if self.rect.bottom < 0:
self.kill()
class Enemy(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = enemy_img
self.rect = self.image.get_rect()
self.rect.x = random.randint(0, SCREEN_WIDTH - self.rect.width)
self.rect.y = random.randint(-SCREEN_HEIGHT, -self.rect.height)
self.speed = random.randint(1, 5)
def update(self):
self.rect.y += self.speed
if self.rect.top > SCREEN_HEIGHT:
self.rect.x = random.randint(0, SCREEN_WIDTH - self.rect.width)
self.rect.y = random.randint(-SCREEN_HEIGHT, -self.rect.height)
self.speed = random.randint(1, 5)
# 创建游戏角色
player = Plane()
enemies = pygame.sprite.Group()
for i in range(10):
enemy = Enemy()
enemies.add(enemy)
# 游戏主循环
while True:
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
# 更新游戏角色
player.update
阅读全文