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)
相关推荐
艾莉丝努力练剑17 分钟前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
橡晟4 小时前
深度学习入门:让神经网络变得“深不可测“⚡(二)
人工智能·python·深度学习·机器学习·计算机视觉
墨尘游子4 小时前
神经网络的层与块
人工智能·python·深度学习·机器学习
倔强青铜34 小时前
苦练Python第18天:Python异常处理锦囊
开发语言·python
u_topian5 小时前
【个人笔记】Qt使用的一些易错问题
开发语言·笔记·qt
企鹅与蟒蛇5 小时前
Ubuntu-25.04 Wayland桌面环境安装Anaconda3之后无法启动anaconda-navigator问题解决
linux·运维·python·ubuntu·anaconda
autobaba5 小时前
编写bat文件自动打开chrome浏览器,并通过selenium抓取浏览器操作chrome
chrome·python·selenium·rpa
珊瑚里的鱼5 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
AI+程序员在路上5 小时前
QTextCodec的功能及其在Qt5及Qt6中的演变
开发语言·c++·qt
xingshanchang5 小时前
Matlab的命令行窗口内容的记录-利用diary记录日志/保存命令窗口输出
开发语言·matlab