用python写一个飞机大战小游戏
时间: 2023-03-15 11:55:45 浏览: 35
好的,以下是一个简单的Python飞机大战小游戏的代码示例:
```
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小
screen_width = 480
screen_height = 700
screen = pygame.display.set_mode((screen_width, screen_height))
# 加载背景图片
background = pygame.image.load('images/background.png')
# 加载飞机图片
plane_img = pygame.image.load('images/plane.png')
plane_rect = plane_img.get_rect()
plane_width = plane_rect.width
plane_height = plane_rect.height
# 加载子弹图片
bullet_img = pygame.image.load('images/bullet.png')
bullet_rect = bullet_img.get_rect()
bullet_width = bullet_rect.width
bullet_height = bullet_rect.height
# 加载敌机图片
enemy_img = pygame.image.load('images/enemy.png')
enemy_rect = enemy_img.get_rect()
enemy_width = enemy_rect.width
enemy_height = enemy_rect.height
# 设置字体
font = pygame.font.Font(None, 36)
# 设置游戏帧率
clock = pygame.time.Clock()
fps = 60
# 定义飞机类
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 - 10
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
elif key_pressed[pygame.K_RIGHT]:
self.rect.x += self.speed
if key_pressed[pygame.K_SPACE]:
self.fire()
# 防止飞机飞出屏幕
if self.rect.left < 0:
self.rect.left = 0
elif self.rect.right > screen_width:
self.rect.right = screen_width
def fire(self):
bullet = Bullet()
bullet.rect.centerx = self.rect.centerx
bullet.rect.bottom = self.rect.top
self.bullets.add(bullet)
# 定义子弹类
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 - enemy_width)
self.rect.y = random.randint(-enemy_height, -10)
self.speed = random.randint(1, 5)
def update(self):
self.rect.y += self.speed
if self.rect.top > screen_height:
self.kill()
# 创建精灵组
all_sprites = pygame.sprite.Group()
# 创建飞机精灵
plane = Plane()
all_sprites.add(plane)
# 创建敌机精灵组
enemies = pygame.sprite.Group()
# 设置初始得分
score = 0
# 游戏主循环
running = True
while running:
阅读全文
相关推荐















