文章目录
前言
记录pygame的精灵类、精灵组类、实现动态效果、图层管理等内容。精灵类–pygame.sprite.Sprite
框架
class Ball(pygame.sprite.Sprite):
def __init__(self...):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(...)
self.rect = self.image.get_rect()
...
def update():
...
ball = Ball(...)
ball.update()
screen.blit(ball.image, ball.rect)
pygame.display.update()
属性和方法
- .image 图像
- .rect 矩形框
- .update() 更新
- .add() 添加到组
- .remove() 从组中移除
- .kill() 从所有组中删除
- .alive() 判断是否存活
精灵组类–pygame.sprite.Group
无序,支持in、len()、bool、iter
框架
BallGroup = pygame.sprite.Group()
BallGroup.add(ball)
...
BallGroup.update(...)
BallGroup.draw()
pygame.display.update()
属性和方法
- .sprites 精灵组列表
- .add() 添加精灵
- .remove() 移除精灵
- .update() 更新
- .draw() 绘制组内所有精灵
- .clear() 绘制背景
- .empty() 清空
- .has() 判断成员存在
- .copy 复制
精灵冲突–pygame.sprite.collide
- pygame.sprite.collide_rect(first_sprite, second_sprite) 判断两个矩形精灵是否碰撞
- pygame.sprite.collide_circle(first_sprite, second_sprite) 判断两个圆形精灵是否碰撞
- pygame.sprite.collideany(sprite, group) 判断精灵与精灵组是否碰撞
- pygame.sprite.spritecollide(sprite, group,bool_kill) 返回精灵组中与精灵碰撞的精灵列表,boll_kill为True时调用kill()
- pygame.sprite.groupcollide(first_group, second_group,bool_kill1, bool_kill1) 返回字典{1中冲突精灵:[2中冲突精灵列表]},boll_kill为True时调用kill()
- pygame.sprite.collide_mask() 判断是否有像素遮盖
精灵组管理–pygame.sprite.LayeredUpdates
allgroup更新、绘制,其他精灵组检测冲突。
allgroup = pygame.sprite.LayeredUpdates()
class Ball(pygame.sprite.Sprite):
def __init__(self...):
self._layer = -1
self.groups = ballgroup, allgroup #创建对象时自动添加到组内
pygame.sprite.Sprite.__init__(self, self.groups)
allgroup.update()
allgroup.draw(screen)
pygame.display.update()
图层管理
- group.get_layer_of_sprite(sprite) 返回当前层
- group.change_layer(sprite, int_layer) 改变图层
- group.get_sprites_at() 返回列表,底部图层在前
- group.switch_layer(int_layer1, int_layer2) 从图层1切换到图层2
动态效果
- 切分图片
self.image = pygame.image.load("./data/shoots_50x50_2.png")
self.images = []
for i in range(2):
self.images.append(self.image.subsurface(i*50, 0, 50, 50))
- 随时间变化
self.lifetime = 0
...
passtime = self.clock.tick()
...
def update(self, passtime)
rate = 50
self.lifetime += passtime
i = (self.lifetime//rate)%2
self.image = self.images[i]
if self.lifetime > 500:
self.lifetime -= 500
- 随位置变化
def update(self)
rate = 50
i = (self.rect.left//rate)%2
self.image = self.images[i]