2014-11-25 41 views
2

我正在製作一個簡單的程序,用於顯示背景圖片併爲僅有3幀的簡單精靈進行動畫處理。我每次運行它,它給我的錯誤在Pygame中使用Sprite表格

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

我一直在努力與這一段時間,我不知道該怎麼辦了。任何幫助將不勝感激,這裏是我的代碼:

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() 
+0

我不明白爲什麼你需要繪製'allSprites'和'collSprites'組。只畫一次會容易得多。 – cweb 2015-03-17 01:57:05

回答

0

您需要更改貓類的update()方法。嘗試是這樣的:

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) 
如果你想知道什麼是你的代碼問題

,你可以打印cat.currentframe值。