Python 飞机大战开发核心:子弹发射与碰撞检测逻辑

1. 子弹发射核心逻辑

实现步骤

  1. 子弹类定义:创建子弹对象,包含位置、速度、图像等属性
class Bullet:
    def __init__(self, x, y):
        self.x = x  # 子弹初始X坐标
        self.y = y  # 子弹初始Y坐标
        self.speed = 10  # 子弹移动速度
        self.image = pygame.Surface((4, 8))  # 子弹尺寸
        self.image.fill((255, 255, 0))  # 黄色子弹
        self.rect = self.image.get_rect(center=(x, y))
    
    def update(self):
        self.y -= self.speed  # 向上移动
        self.rect.center = (self.x, self.y)

  1. 发射控制:在玩家飞机类中添加发射方法
class Player:
    def __init__(self):
        # ... 飞机初始化代码
        self.bullets = []  # 存储子弹对象
        self.shoot_cooldown = 0  # 射击冷却
    
    def shoot(self):
        if self.shoot_cooldown == 0:
            # 在飞机头部位置创建子弹
            new_bullet = Bullet(self.rect.centerx, self.rect.top)
            self.bullets.append(new_bullet)
            self.shoot_cooldown = 15  # 设置冷却时间
    
    def update(self):
        # 更新冷却时间
        if self.shoot_cooldown > 0:
            self.shoot_cooldown -= 1
        
        # 更新子弹位置
        for bullet in self.bullets[:]:
            bullet.update()
            if bullet.y < 0:  # 移除超出屏幕的子弹
                self.bullets.remove(bullet)

  1. 主循环触发:在游戏主循环中检测射击按键
running = True
while running:
    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:  # 空格键发射
                player.shoot()
    
    # 更新游戏状态
    player.update()
    
    # 渲染子弹
    for bullet in player.bullets:
        screen.blit(bullet.image, bullet.rect)

2. 碰撞检测核心逻辑

碰撞检测类型

  1. 子弹与敌机碰撞
  2. 玩家与敌机碰撞
  3. 玩家与道具碰撞

实现方法

# 使用pygame的碰撞检测函数
def check_collisions():
    # 子弹与敌机碰撞检测
    for bullet in player.bullets[:]:
        for enemy in enemies[:]:
            if bullet.rect.colliderect(enemy.rect):
                player.bullets.remove(bullet)
                enemies.remove(enemy)
                # 增加得分
                score += 100
                break
    
    # 玩家与敌机碰撞检测
    for enemy in enemies:
        if player.rect.colliderect(enemy.rect):
            # 玩家生命值减少
            player.health -= 10
            enemies.remove(enemy)
            if player.health <= 0:
                game_over()
    
    # 玩家与道具碰撞检测
    for item in items:
        if player.rect.colliderect(item.rect):
            # 根据道具类型增强玩家能力
            if item.type == "shield":
                player.health += 20
            items.remove(item)

3. 完整核心代码框架
import pygame
import random

# 初始化pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))

# 玩家类
class Player:
    def __init__(self):
        self.image = pygame.Surface((50, 40))
        self.image.fill((0, 255, 0))
        self.rect = self.image.get_rect(center=(400, 500))
        self.bullets = []
        self.shoot_cooldown = 0
        self.health = 100
    
    def shoot(self):
        if self.shoot_cooldown == 0:
            self.bullets.append(Bullet(self.rect.centerx, self.rect.top))
            self.shoot_cooldown = 10
    
    def update(self):
        # 更新子弹
        for bullet in self.bullets[:]:
            bullet.update()
            if bullet.rect.bottom < 0:
                self.bullets.remove(bullet)
        
        # 更新冷却
        if self.shoot_cooldown > 0:
            self.shoot_cooldown -= 1

# 子弹类
class Bullet:
    def __init__(self, x, y):
        self.image = pygame.Surface((4, 15))
        self.image.fill((255, 255, 0))
        self.rect = self.image.get_rect(center=(x, y))
    
    def update(self):
        self.rect.y -= 12  # 向上移动

# 敌机类
class Enemy:
    def __init__(self):
        self.image = pygame.Surface((40, 40))
        self.image.fill((255, 0, 0))
        self.rect = self.image.get_rect(center=(random.randint(0, 800), -50))
        self.speed = random.randint(2, 5)
    
    def update(self):
        self.rect.y += self.speed

# 主游戏循环
player = Player()
enemies = []
clock = pygame.time.Clock()
score = 0

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_SPACE:
                player.shoot()
    
    # 生成敌机
    if random.random() < 0.02:
        enemies.append(Enemy())
    
    # 更新对象
    player.update()
    for enemy in enemies:
        enemy.update()
    
    # 碰撞检测
    for bullet in player.bullets[:]:
        for enemy in enemies[:]:
            if bullet.rect.colliderect(enemy.rect):
                player.bullets.remove(bullet)
                enemies.remove(enemy)
                score += 100
                break
    
    # 渲染
    screen.fill((0, 0, 0))
    screen.blit(player.image, player.rect)
    for bullet in player.bullets:
        screen.blit(bullet.image, bullet.rect)
    for enemy in enemies:
        screen.blit(enemy.image, enemy.rect)
    
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

4. 优化建议
  1. 使用精灵组pygame.sprite.Group()管理子弹和敌机
  2. 碰撞掩码:使用pygame.mask.from_surface()实现像素级碰撞检测
  3. 对象池:复用子弹对象减少内存分配
  4. 粒子效果:碰撞时添加爆炸特效
  5. 空间分割:使用四叉树优化大量对象的碰撞检测

通过以上核心逻辑实现,即可完成飞机大战的基本战斗系统。实际开发中可根据需求添加更多功能,如多种武器系统、敌机类型、Boss战等。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐