帮我生成一份飞机大战中敌机可以自动发射子弹的代码
时间: 2024-03-18 22:43:06 浏览: 117
python游戏代码,雷霆战机,纯python编程,可以发射不同的子弹,内含多种飞机供驾驶
5星 · 资源好评率100%
好的,以下是一个简单的示例代码,实现了敌机自动发射子弹的功能:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 游戏窗口尺寸
WINDOW_WIDTH = 480
WINDOW_HEIGHT = 800
# 创建游戏窗口
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('飞机大战')
# 加载图片资源
background_img = pygame.image.load('images/background.png')
player_img = pygame.image.load('images/player.png')
bullet_img = pygame.image.load('images/bullet.png')
enemy_img = pygame.image.load('images/enemy.png')
# 定义游戏角色类
class Actor:
def __init__(self, img, x, y):
self.img = img
self.rect = img.get_rect()
self.rect.centerx = x
self.rect.centery = y
def draw(self, screen):
screen.blit(self.img, self.rect)
# 定义玩家类
class Player(Actor):
def __init__(self, img, x, y):
super().__init__(img, x, y)
self.speed = 5
self.bullets = []
def move_left(self):
self.rect.centerx -= self.speed
def move_right(self):
self.rect.centerx += self.speed
def fire(self):
bullet = Bullet(bullet_img, self.rect.centerx, self.rect.top)
self.bullets.append(bullet)
def draw_bullets(self, screen):
for bullet in self.bullets:
bullet.move()
bullet.draw(screen)
if bullet.rect.bottom < 0:
self.bullets.remove(bullet)
# 定义子弹类
class Bullet(Actor):
def __init__(self, img, x, y):
super().__init__(img, x, y)
self.speed = 10
def move(self):
self.rect.centery -= self.speed
# 定义敌机类
class Enemy(Actor):
def __init__(self, img, x, y):
super().__init__(img, x, y)
self.speed = 3
self.direction = random.choice([-1, 1])
self.fire_interval = 60
self.fire_countdown = self.fire_interval
def move(self):
self.rect.centerx += self.speed * self.direction
if self.rect.left < 0 or self.rect.right > WINDOW_WIDTH:
self.direction *= -1
self.rect.centery += 50
def fire(self):
bullet = Bullet(bullet_img, self.rect.centerx, self.rect.bottom)
return bullet
# 创建玩家对象
player = Player(player_img, WINDOW_WIDTH // 2, WINDOW_HEIGHT - 100)
# 创建敌机列表
enemies = []
for i in range(5):
enemy = Enemy(enemy_img, random.randint(50, WINDOW_WIDTH - 50), random.randint(-500, -50))
enemies.append(enemy)
# 游戏主循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.move_left()
elif event.key == pygame.K_RIGHT:
player.move_right()
elif event.key == pygame.K_SPACE:
player.fire()
# 绘制背景
screen.blit(background_img, (0, 0))
# 绘制玩家
player.draw(screen)
player.draw_bullets(screen)
# 绘制敌机
for enemy in enemies:
enemy.move()
enemy.draw(screen)
enemy.fire_countdown -= 1
if enemy.fire_countdown <= 0:
bullet = enemy.fire()
player.bullets.append(bullet)
enemy.fire_countdown = enemy.fire_interval
# 更新屏幕
pygame.display.update()
# 延迟一段时间,控制游戏帧率
pygame.time.delay(10)
```
这段代码实现了一个简单的飞机大战游戏,其中敌机会自动发射子弹。你可以将代码保存为一个 Python 文件,然后在命令行中运行该文件,即可开始游戏。希望能够帮到你!
阅读全文