Reputation: 157
I want to have an animated backround in pygame
, and since I didn't find any bette soulutions, I have decided to make it with the help of sprites
. As far as I know, pygame doesn't support video files, I split the video into frames and made a code like this:
class BackgroundAnimator(pygame.sprite.Sprite):
def __init__(self,pos_x,pos_y):
super().__init__()
self.sprites = []
self.is_animating = False
self.sprites.append(pygame.transform.scale(pygame.image.load(os.path.join("Textures", "backgroundframe1.jpg")),(WIDTH,HEIGHT)))
here I would have to copy this line like 200 times so each frame would be in the sprite
self.current_sprite = 0
self.image = self.sprites[self.current_sprite]
self.rect = self.image.get_rect()
self.rect.topleft = [pos_x,pos_y]
def animate(self):
self.is_animating=True
def update(self):
if self.is_animating == True:
self.current_sprite += 0.14
if self.current_sprite >= len(self.sprites):
self.current_sprite = 0
self.image=self.sprites[int(self.current_sprite)]
moving_backgroundsprites = pygame.sprite.Group()
backgroundlocation = BackgroundAnimator(0,0)
There is probably a way better solution than this, but I have no idea where to begin. Or how can i load all images without having to paste the same line 200 times, and change the name of the file (so for example backgroundframe1 and then backgroundframe2 and the 3 and so on)?
Upvotes: 1
Views: 40
Reputation: 210968
Just concatenate the name and the number. The number can be converted to a string with the str
function:
for i in range(1, 100):
filename = "backgroundframe" + str(i) + ".jpg"
Alternatively use f-strings:
for i in range(1, 100):
filename = f"backgroundframe{i}.jpg"
e.g.:
class BackgroundAnimator(pygame.sprite.Sprite):
def __init__(self,pos_x,pos_y, filename):
super().__init__()
self.sprites = []
self.is_animating = False
path = os.path.join("Textures", filename)
self.sprites.append(pygame.transform.scale(pygame.image.load(path),(WIDTH,HEIGHT)))
no_of_frames = 100 # depends on the number of files
moving_backgroundsprites = pygame.sprite.Group()
for i in range(1, no_of_frames):
filename = f"backgroundframe{i}.jpg"
backgroundlocation = BackgroundAnimator(0, 0, filename)
moving_backgroundsprites.add(backgroundlocation)
Upvotes: 1