生成一个飞机大战python代码
时间: 2024-01-07 09:02:18 浏览: 23
以下是一个简单的飞机大战Python代码示例,你可以在此基础上进行修改和扩展:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小和标题
WINDOW_WIDTH = 480
WINDOW_HEIGHT = 800
WINDOW_TITLE = '飞机大战'
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption(WINDOW_TITLE)
# 加载背景和飞机图片
bg_img = pygame.image.load('images/bg.jpg')
player_img = pygame.image.load('images/player.png')
enemy_img = pygame.image.load('images/enemy.png')
bullet_img = pygame.image.load('images/bullet.png')
# 设置游戏时钟和帧率
clock = pygame.time.Clock()
FPS = 60
# 飞机类
class Plane(pygame.sprite.Sprite):
def __init__(self, img, x, y, speed):
super().__init__()
self.image = img
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.speed = speed
def update(self):
self.rect.y += self.speed
# 玩家类
class Player(Plane):
def __init__(self, img, x, y, speed):
super().__init__(img, x, y, speed)
self.bullets = pygame.sprite.Group()
def update(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.rect.x -= self.speed
if keys[pygame.K_RIGHT]:
self.rect.x += self.speed
if keys[pygame.K_SPACE]:
bullet = Bullet(bullet_img, self.rect.centerx, self.rect.top)
self.bullets.add(bullet)
# 敌机类
class Enemy(Plane):
def __init__(self, img, x, y, speed):
super().__init__(img, x, y, speed)
# 子弹类
class Bullet(pygame.sprite.Sprite):
def __init__(self, img, x, y):
super().__init__()
self.image = img
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.bottom = y
self.speed = -10
def update(self):
self.rect.y += self.speed
if self.rect.bottom < 0:
self.kill()
# 创建玩家和敌机精灵组
player = Player(player_img, WINDOW_WIDTH // 2, WINDOW_HEIGHT - 100, 5)
enemies = pygame.sprite.Group()
# 游戏主循环
while True:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
# 更新玩家和敌机
player.update()
enemies.update()
# 添加新的敌机
if random.randint(1, 60) == 1:
enemy = Enemy(enemy_img, random.randint(0, WINDOW_WIDTH - 50), -50, random.randint(1, 5))
enemies.add(enemy)
# 检测玩家和敌机是否碰撞
if pygame.sprite.spritecollide(player, enemies, False):
pygame.quit()
exit()
# 检测子弹和敌机是否碰撞
for bullet in player.bullets:
if pygame.sprite.spritecollide(bullet, enemies, True):
bullet.kill()
# 绘制游戏界面
screen.blit(bg_img, (0, 0))
screen.blit(player.image, player.rect)
player.bullets.draw(screen)
enemies.draw(screen)
# 更新游戏界面
pygame.display.update()
# 控制游戏帧率
clock.tick(FPS)
```
在运行该代码之前,需要先准备好游戏需要用到的图片素材,并将其放置在代码中对应的路径下。
阅读全文