Using Sprite Sheets in Pygame

633 views Asked by At

I am making a simple program that displays a background image and animates a simple sprite with only 3 frames. Every time I run it, it gives me the error

screen.blit(firstexp[currentimage], (xpos,ypos)) IndexError: list index out of range

I've been working with this for a while now and I'm not sure what to do anymore. Any help would be greatly appreciated, here's my code:

import pygame, sys, random
from pygame.locals import *
pygame.init()

class Cat(pygame.sprite.Sprite):
    animationArray = []
    numframes = 0
    currentframe = 0
    anispeed = 0
    lastdraw = 0
    xspeed = 5
    xpos = 10
    ypos = 10

    def __init__(self, imgname, startx, starty, w, h, numframes, anispeed):
        pygame.sprite.Sprite.__init__(self)
        spsheet = pygame.image.load(imgname)
        f1 = spsheet.subsurface(0,0,120,60)
        self.animationArray.append(f1)
        f2 = spsheet.subsurface(0,60,120,60)
        self.animationArray.append(f2)
        f3 = spsheet.subsurface(0,120,120,60)
        self.animationArray.append(f3)

        self.numframes = 3
        self.currentframe = 0
        self.anispeed = anispeed

    def update(self, secs):
        self.xpos = self.xpos + self.xspeed
        self.lastdraw = self.lastdraw+secs
        if self.lastdraw     self.anispeed:
            self.currentframe = self.currentframe+1
            if self.currentframe==2:
                self.currentframe=0
            self.lastdraw = 0

        self.image = self.animationArray[self.currentframe]
        self.rect = (self.xpos,0,0,120,180)

         def setEnv(background):
    clock = pygame.time.Clock()
    backimage = pygame.image.load(background)
    w = backimage.get_rect().w
    h = backimage.get_rect().h
    screen = pygame.display.set_mode((w,h))

    return clock, backimage, screen


###main game code

clock, backimage, screen = setEnv("landscape-illustration.jpg")

allSprites = pygame.sprite.Group() collSprites = pygame.sprite.Group()

catx = Cat("runningcat.png", 0,0,120,180,3,1) 

allSprites.add(catx)
collSprites.add(catx)    
screen.blit(backimage,(0,0))
while True:
    secs = clock.tick(30)/1000
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            sys.exit()

    allSprites.clear(screen, backimage)
    allSprites.update(secs)
    allSprites.draw(screen)
    collSprites.draw(screen)
    pygame.display.flip()
1

There are 1 answers

0
Sudesh On

You need to change the update() method of Cat class. Try something like this :

def update(self, secs):
    self.xpos += self.xspeed
    self.lastdraw += secs
    if self.lastdraw > self.anispeed:
        self.currentframe = (self.currentframe+1) % 3
    self.lastdraw = 0

self.image = self.animationArray[self.currentframe]
self.rect = (self.xpos,0,0,120,180)

if you want to know what is problem with your code, you can print value of cat.currentframe.