[英]How does the python sprite list work? Can i add sprite coords to the list?
Hello there dear friends, for my python project, I made a button class -and their images, coords, actions and so on- and things working good. 亲爱的朋友们,您好,对于我的python项目,我创建了一个按钮类-它们的图像,坐标,动作等,并且一切正常。 But I think I will add lots of buttons in the game so I decided to add them to a one pygame sprite group with their coordinates and blit automatically with a for loop. 但是我想我会在游戏中添加很多按钮,所以我决定将它们的坐标添加到一个pygame sprite组中,并使用for循环自动使其变亮。
for oge in buttonList:
pygame.blit(oge, (x, y)
is there a way can I add sprites with their coords to groups or lists, to blit them all together? 有什么办法可以将带有其坐标的子画面添加到组或列表中,以将它们全部合并?
Short answer: 简短答案:
If each sprite has an attribute .rect
and .image
, then you can call .draw()
: 如果每个精灵都有一个.rect
和.image
属性,则可以调用.draw()
:
buttonList.draw(surf)
Long answer: 长答案:
A pygame.sprite.Sprite
object should have a .rect
property of type pygame.Rect
this attribute defines the position (and size) of the sprite. pygame.sprite.Sprite
对象应该具有.rect
类型的pygame.Rect
属性pygame.Rect
此属性定义了Sprite的位置(和大小)。
In the following I assume that buttonList
is a pygame.sprite.Group
. 在下文中,我假设buttonList
是pygame.sprite.Group
。
Each Sprite in the Group shuold have a .rect
property which is used to draw the sprite at its location eg: 组shuold中的每个Sprite都具有.rect
属性,该属性用于在其位置绘制Sprite,例如:
class MySprite(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = [...]
self.rect = self.image.get_rect()
All the sprite of the group can be drawn by on call. 该组中的所有子画面都可以通过调用来绘制。 The parameter surf
can be any surface, eg the display surface: 参数surf
可以是任何表面,例如显示表面:
buttonList.draw(surf)
Note, the draw()
method of the pygame.sprite.Group
draws the contained Sprites onto the Surface. 注意, pygame.sprite.Group
的draw()
方法将包含的pygame.sprite.Group
绘制到Surface上。 The .image
of each sprite is "blit" at the location .rect
. 每个精灵的.image
在.rect
位置“ .rect
。
pygame.Rect
has a lot of virtual attributes, to set its position (and size) eg .center
or .topleft
. pygame.Rect
具有很多虚拟属性,可以设置其位置(和大小),例如.center
或.topleft
。 Use them to set the position of the sprite: 使用它们来设置精灵的位置:
mysprite = MySprite()
mysprite.rect.topleft = (x, y)
Of course, the position (x, y)
can be a parameter the constructor of the sprite class, too: 当然,位置(x, y)
也可以是sprite类的构造函数的参数:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.