亲爱的朋友们,你好, 对于我的 Python 项目,我创建了一个按钮类 - 以及它们的图像、坐标、动作等——并且运行良好。但我想我会在游戏中添加很多按钮,所以我决定将它们添加到一个带有坐标的pygame精灵组中,并使用for循环自动闪电。
for oge in buttonList:
pygame.blit(oge, (x, y)
有没有办法将精灵及其坐标添加到组或列表中,将它们全部拼凑在一起?
简短回答:
如果每个精灵都有一个属性.rect
和.image
,那么你可以调用.draw()
:
buttonList.draw(surf)
长答案:
pygame.sprite.Sprite
对象应具有类型.rect
属性pygame.Rect
此属性定义子画面的位置(和大小(。
在下文中,我假设buttonList
是一个pygame.sprite.Group
。
组中的每个精灵都有一个.rect
属性,用于在其位置绘制精灵,例如:
class MySprite(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = [...]
self.rect = self.image.get_rect()
该组的所有精灵都可以随叫随到。参数surf
可以是任何表面,例如显示表面:
buttonList.draw(surf)
请注意,pygame.sprite.Group
的draw()
方法将包含的精灵绘制到曲面上。每个精灵的.image
在位置.rect
是"闪电战"。
pygame.Rect
有很多虚拟属性,可以设置它的位置(和大小(,例如.center
或.topleft
.使用它们来设置精灵的位置:
mysprite = MySprite()
mysprite.rect.topleft = (x, y)
当然,位置(x, y)
也可以是精灵类构造函数的参数:
class MySprite(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = [...]
self.rect = self.image.get_rect(topleft = (x, y))
mysprite = MySprite(x, y)