Can i let a for n in range keep going despite item

Question:

I relatively new to coding, so I need a bit of help figuring this out.

I’m creating a game using pygame, and I have a for n in range loop that sorts through the characters ‘frames’ for the animations. The issue I’m having here is that the players’ death animation is 11 frames while the enemy is only 4 frames when loading the enemy’s death animation. So the for loop fails due to it not finding more frames. I was wondering if there was a way to potentially make it ignore the fact that there are no more frames or another solution, perhaps. I’ll put the piece of code below. Thank you.

tempList = []
    for n in range(11):
        img = pygame.image.load(
            f'C:\Users\ASUS\OneDrive\Desktop\Game\Imgs\Sprites\{self.name}\Dead\tile{n}.png')
        img = pygame.transform.scale(img, (img.get_width() * 2.5, img.get_width() * 2.5))
        tempList.append(img)
    self.animationList.append(tempList)
Asked By: Abdulrahman

||

Answers:

you can use the os module to check if the file exists before loading/transforming throws an error with a file that isn’t there.

from os.path import exists


tempList = []
    for n in range(11):
        filename = f'C:\Users\ASUS\OneDrive\Desktop\Game\Imgs\Sprites\{self.name}\Dead\tile{n}.png'
        if os.path.exists(filename) is False:
            continue 
        img = pygame.image.load(filename)
        img = pygame.transform.scale(img, (img.get_width() * 2.5, img.get_width() * 2.5))
        tempList.append(img)
    self.animationList.append(tempList)
Answered By: Chris B
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.