Reputation: 25
I'm making a game and I created a loop in a class that creates a list with every sprite I need from my sprite sheet.
The problem is that when I try to blit an element of the list, I always get this error: IndexError: list index out of range
Here's the code of the function in the class (simplified):
def sprites(self):
i = 1
boxwidth = 0
boxwidthend = False
sprites = []
for i in range(1,0,5):
while i <= 2:
boxheight = 0
spritesurface = pygame.Surface((self.width, self.heightside), pygame.SRCALPHA)
spritesurface.blit(self.type, (0,0), (0 + boxwidth, 0, self.width, self.heightside))
sprite = pygame.transform.scale(spritesurface, (self.width * self.scale, self.heightside * self.scale))
sprites.append(sprite)
while i <= 5:
boxheight = 49
if boxwidthend == False:
boxwidth = 0
boxwidthend = True
spritesurface = pygame.Surface((self.width, self.heightup), pygame.SRCALPHA)
spritesurface.blit(self.type, (0,0), (0 + boxwidth, boxheight, self.width, self.heightup))
sprite = pygame.transform.scale(spritesurface, (self.width * self.scale, self.heightup * self.scale))
sprites.append(sprite)
boxwidth += 25
i += 1
return sprites
and here's the main code section (simplified):
sprites_class = GetSprites("human", 3)
spritelist = sprites_class.sprites()
while True:
ROOT.blit(spritelist[3], (playermovement.x, playermovement.y))
Upvotes: 0
Views: 63
Reputation: 50200
Summarizing the comments:
Range takes three parameters
So if you want to loop numbers 1
through 5
, all you need is Range(6)
as the optional start
parameter defaults to 0
and the optional step
parameter defaults to 1
.
while i<=2:
will result in an infinite loop as there is no way for the value of i
to change inside the loop. Once you enter it, it will go on forever. Instead you want an if
and elif
def sprites(self):
boxwidth = 0
boxwidthend = False
sprites = []
for i in range(6):
if i <= 2:
print("i <= 2")
boxwidth += 1
boxheight = 0
spritesurface = pygame.Surface((self.width, self.heightside), pygame.SRCALPHA)
spritesurface.blit(self.type, (0,0), (0 + 25 * boxwidth, 0, self.width, self.heightside))
sprite = pygame.transform.scale(spritesurface, (self.width * self.scale, self.heightup * self.scale))
sprites.append(sprite)
elif i <= 5:
print("i > 2")
boxheight = 48
if boxwidthend == False:
boxwidth = 0
boxwidthend = True
spritesurface = pygame.Surface((self.width, self.heightup), pygame.SRCALPHA)
spritesurface.blit(self.type, (0,0), (0 + 25 * boxwidth, boxheight, self.width, self.heightup))
sprite = pygame.transform.scale(spritesurface, (self.width * self.scale, self.heightup * self.scale))
sprites.append(sprite)
return sprites
Upvotes: 1