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)
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)
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)
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)