I have a simple top down vertical shooter a la Galaga that I’m messing around with. However, after looking through the documentation I’ve become a bit confused on how to efficiently load images, and whether to blit them every frame or not. All of the images are loaded through a few classes which inherit the pygame sprite class. At the moment, I’m loading the image as a class level attribute as such:
class Laser(pygame.sprite.Sprite):
image = None
def __init__(self, start_x, start_y):
pygame.sprite.Sprite.__init__(self)
self.pos_x = start_x
self.pos_y = start_y
if Laser.image is None:
Laser.image = pygame.image.load('img/laser_single.png')
self.image = Laser.image
self.rect = self.image.get_rect()
self.rect.topleft = [self.pos_x, self.pos_y]
I’m hoping this prevents Python from loading a new instance of the image into memory every time I create a new Laser(). But will this work as I anticipate?
The second issue stems from blitting all of the active sprites onto the pygame surface. At the moment I loop through a list of Laser(), Enemy(), and whatnot objects and blit each one individually before calling pygame.display.update(). It seems redundant to have to blit each object individually, so I’m asking whether or not this is the most efficient method pygame implements. Or, is there a way to blit every object at once and see some sort of performance improvement?
Yes. Not only does this save memory, since every instance will just have a reference to the class variable, it will also increase performance because the image is only loaded once.
This depends. If your framerate is OK, then stick with it. If your framerate starts dropping, have a look at
DirtySprite, and maybe this article.Another python class that comes in handy is the
LayeredDirtysprite group, which will automatically handle dirty sprites and updating only the relevant screen parts instead of the entire screen for you.With sprite groups, as e.g. the
LayeredDirtyor the simpleGroup, you add your sprites to the group once and just call thedrawmethod of the sprite group.Using sprite groups will also enable you to do simple collision detection between groups using
pygame.sprite.groupcollideandpygame.sprite.spritecollideany