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. 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.
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()
:
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.
In the following I assume that buttonList
is a pygame.sprite.Group
.
Each Sprite in the Group shuold have a .rect
property which is used to draw the sprite at its location e.g.:
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, e.g. the display surface:
buttonList.draw(surf)
Note, the draw()
method of the pygame.sprite.Group
draws the contained Sprites onto the Surface. The .image
of each sprite is "blit" at the location .rect
.
pygame.Rect
has a lot of virtual attributes, to set its position (and size) e.g. .center
or .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:
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)