在Pygame中使用Sprite表格

时间:2014-11-25 00:15:09

标签: python pygame sprite sprite-sheet

我正在创建一个简单的程序,它显示一个背景图像并动画一个只有3帧的简单精灵。每次我运行它,它都会给我错误

  

screen.blit(firstexp [currentimage],(xpos,ypos))IndexError:list   指数超出范围

我现在已经使用了一段时间了,我不知道该怎么做了。任何帮助将不胜感激,这是我的代码:

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 个答案:

答案 0 :(得分:0)

您需要更改Cat类的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的值。