Pygame基础9-射击

简介

玩家用鼠标控制飞机(白色方块)移动,按下鼠标后,玩家所在位置出现子弹,子弹匀速向右飞行。

代码

没有什么新的东西,使用两个精灵类表示玩家和子弹。

有一个细节需要注意,当子弹飞出屏幕时,要将子弹清除(kill)。(否则虽然看不见子弹了,但是子弹还是(一直)存在,会占用内存。

python 复制代码
import pygame
import sys

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((50, 50))
        self.image.fill((255, 255, 255))
        self.rect = self.image.get_rect(center = (screen_size[0]//2, screen_size[1]//2))
    def update(self):
        self.rect.center = pygame.mouse.get_pos()
    def shoot(self):
        return Bullet(self.rect.centerx, self.rect.centery)
        

class Bullet(pygame.sprite.Sprite):
    def __init__(self,pos_x, pos_y):
        super().__init__()
        self.image = pygame.Surface((50, 10))
        self.image.fill((255, 0, 0))
        self.rect = self.image.get_rect(center = (pos_x, pos_y))
        self.speed = 5
    def update(self):
        self.rect.x += self.speed
        # 如果子弹超出屏幕,就删除。否则子弹会(在屏幕外)一直存在。
        if self.rect.right > screen_size[0] + 20:
            self.kill()

# 初始化
pygame.init()
screen_size = (800, 600)
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption("Pygame Demo")
clock = pygame.time.Clock()

pygame.mouse.set_visible(False)

player = Player()
player_group = pygame.sprite.Group()
player_group.add(player)

bullet_group = pygame.sprite.Group()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            bullet = player.shoot()
            bullet_group.add(bullet)

    # update
    # draw
    screen.fill((0, 0, 0))   
    # 先画子弹,再画玩家,否则玩家会被子弹挡住。
    bullet_group.update()
    bullet_group.draw(screen)
    
    player_group.update()
    player_group.draw(screen)
    
    pygame.display.flip()
    clock.tick(60)
相关推荐
这里有鱼汤1 小时前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩11 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在16 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP18 小时前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户8356290780511 天前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
c8i1 天前
python中类的基本结构、特殊属性于MRO理解
python
echoarts1 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
liwulin05061 天前
【ESP32-CAM】HELLO WORLD
python
Aomnitrix1 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式