在python中使用spritesheet时,我一直遇到一个错误

在python中使用spritesheet时,我一直遇到一个错误,python,pygame,Python,Pygame,我在尝试运行代码时遇到了两个错误,但可能还有更多错误,因为这是我第一次使用spritesheets。 第一个错误是,当调用spritesheet时,它给了我一个错误,说我给出了4个参数,而它只需要3个参数。不过,我似乎只看到3个论点。第二个错误是此代码行无法调用“tuple”对象:(-1*半spriteWidth,-1*spriteHeight),(-1*spriteWidth,-1*spriteHeight)]。有人能帮我弄清楚吗 class spritesheet: def __in

我在尝试运行代码时遇到了两个错误,但可能还有更多错误,因为这是我第一次使用spritesheets。 第一个错误是,当调用spritesheet时,它给了我一个错误,说我给出了4个参数,而它只需要3个参数。不过,我似乎只看到3个论点。第二个错误是此代码行无法调用“tuple”对象:
(-1*半spriteWidth,-1*spriteHeight),(-1*spriteWidth,-1*spriteHeight)]
。有人能帮我弄清楚吗

class spritesheet:
    def __init__(filename,columns,rows):
        sheet = image.load(filename)
        totalCellCount = columns * rows
        rect = sheet.get_rect()
        spriteWidth = cellWidth = rect.width / columns
        spriteHeight = cellHeight = rect.height / rows
        halfSpriteWidth, halfSpriteHeight = cellCenter = (spriteWidth/2,spriteHeight/2)
        cells = list([(index % columns * spriteWidth, index / columns * spriteHeight,spriteWidth,spriteHeight)for index in range(totalCellCount)])
        handle = list([
            (0,0), (-1*halfSpriteWidth,0),(-1*spriteWidth,0),
            (0,-1*halfSpriteHeight),(-1*halfSpriteWidth,-1*halfSpriteHeight),
            (-1*spriteWidth,-1*halfSpriteHeight),(0,-1*spriteHeight)
            (-1*halfSpriteWidth,-1*spriteHeight),(-1*spriteWidth,-1*spriteHeight)])
        def draw(surface,cellIndex, x,y,handle = 0):
            surface.blit(self.sheet(x + handle[handle][0], y + handle[handle][1]),cells[cellIndex])

player = spritesheet('player.png',4,4)
centerHandle = 4
index = 0

您完全忘记了
self
参数。您的
\uuuu init\uuuu
方法应为:

def __init__(self,filename,columns,rows):
而且:

def draw(self,surface,cellIndex, x,y,handle = 0):
不要忘记,实例应该记住的属性也需要一个
self

您可能想要:

def __init__(filename,columns,rows):
    self.sheet = image.load(filename)
    self.totalCellCount = columns * rows
    self.rect = self.sheet.get_rect()
    #...
    self.handle = list([
        (0,0), (-1*halfSpriteWidth,0),(-1*spriteWidth,0),
        (0,-1*halfSpriteHeight),(-1*halfSpriteWidth,-1*halfSpriteHeight),
        (-1*spriteWidth,-1*halfSpriteHeight),(0,-1*spriteHeight)
        (-1*halfSpriteWidth,-1*spriteHeight),(-1*spriteWidth,-1*spriteHeight)])
当您参考列表时,在
draw
中也可以使用
self.handle
。顺便说一下,也不需要调用
list
,方括号就足够了

元组错误是由于
self.handle
列表中两个元组之间缺少逗号造成的:

(0,-1*spriteHeight)(-1*halfSpriteWidth,-1*spriteHeight),
                  ^^^ insert comma here

类的方法会自动接收一个初始参数,该参数通常命名为
self
,实例正在创建中,因此当调用
spritesheet('player.png',4,4)
时,会添加这个额外的参数。将init函数更改为 DEF*IONITY(自已、文件名、列、行):< /代码>。元组错误是什么?在<代码>结束时,您缺少一个逗号(-* 1×SpReSead宽度,-1×半SpRITeHead),(0,-1*SpReIeHead)。如果答案是有用的,请考虑接受/投票表决。OP不能否决你的答案,所以我会尽力的-他们可以接受你的答案…