alien_invasion之bullet

在学习实现alien_invasion这个项目的时候,遇到了bullet这个class,需要用到pygame的Sprite和Group,觉得不好理解,所以把bullet的相关功能单独抽取出来。简化为在屏幕底部开火,今后再整合到整个项目中。

import sys
import pygame
from pygame.sprite import Sprite
from pygame.sprite import Group

class Bullet(Sprite):
    def __init__(self,screen):
        super().__init__()
        self.screen = screen
        self.rect = pygame.Rect(0,0,3,15)
        # 将发射位置简化为屏幕底部中央
        self.rect.centerx = screen.get_rect().centerx
        self.rect.bottom = screen.get_rect().bottom
    
    # 子弹向上飞
    def update(self):
        self.rect.y -= 1
    
    # 绘制子弹
    def draw_bullet(self):
        pygame.draw.rect(self.screen,(60,60,60),self.rect)

# 对编组中的子弹进行位置更新和删除
def update_bullets(bullets):
    
    # 更新所有子弹的位置
    bullets.update()

    # 删除飞出屏幕的子弹
    for bullet in bullets.copy():    # 必须使用.copy()
        if bullet.rect.bottom <= 0:
            bullets.remove(bullet)

# 开火,控制屏幕上最多子弹数量为3个
def fire_bullet(bullets,screen):
    if len(bullets) < 3:
        new_bullet = Bullet(screen)
        bullets.add(new_bullet)
    

pygame.init()
screen = pygame.display.set_mode((1200,800))

bullets = Group()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                fire_bullet(bullets,screen)

    screen.fill((230,230,230))

    # 绘制编组中的每个子弹
    for bullet in bullets.sprites():
        bullet.draw_bullet()

    update_bullets(bullets)

    pygame.display.flip()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

逆旅匆匆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值