首页 > 解决方案 > blit 错误的目标位置无效,看不到如何

问题描述

我正在编写一个基本上使用精灵的游戏,我为此代码使用了精灵表并最终得到了

“blit 的目的地无效”

错误。

class spritesheet:
    def __init__(self, filename, cols, rows):
        self.sheet = pygame.image.load(filename).convert_alpha()

        self.cols = cols
        self.rows = rows
        self.totalCellCount = cols * rows

        self.rect = self.sheet.get_rect()
        w = self.cellWidth = self.rect.width / cols
        h = self.cellHeight = self.rect.height / rows
        hw, hh = self.cellCenter = (w / 2, h / 2)

        self.cells = list([(index % cols * w, index / cols * h, w, h) for index in range(self.totalCellCount)])
        self.handle = list([
            (0,0), (-hw, 0), (-w, 0),
            (0, -hh), (-hw, -hh), (-w, -hh),
            (0, -h), (-hw, -h), (-w, -h),])

    def draw(self, surface, cellIndex, x, y, handle = 0):
        surface.blit(self.sheet, (x + self.handle[handle][0], y + self.handle[handle][1], self.cells[cellIndex]))


s = spritesheet('Number18.png', 6, 58)


CENTER_HANDLE = 4

Index = 0

#mainloop
run = True
while run:

    s.draw(DS, Index % s.totalCellCount, HW, HH, CENTER_HANDLE)
    Index +=1

    pygame.draw.circle(DS, WHITE, (HW, HW), 2, 0)

    pygame.display.update()
    CLOCK.tick(FPS)
    DS.fill(BLACK)

这基本上是我的全部代码,我遇到了问题

 surface.blit(self.sheet, (x + self.handle[handle][0], y + self.handle[handle][1], self.cells[cellIndex]))

不断给出这是一个无效的目标位置的错误blit,我也注意到我的索引也对它有影响,但我不知道该怎么做。

标签: pythonpython-3.xpygamepython-requests

解决方案


第二个(dest)参数pygame.Surface必须是位置(元组(x, y))或矩形(元组(x, y, h, w))。

你要做的是传递一个元组(x, y, list)

surface.blit(self.sheet, 
    (x + self.handle[handle][0], y + self.handle[handle][1], self.cells[cellIndex]))

如果你想通过 的位置(x + self.handle[handle][0], y + self.handle[handle][1])和宽度和高度来设置目的地self.cells[cellIndex],那么它必须是:

 hdl = self.handle[handle]
 cell = self.cells[cellIndex]
 surface.blit(self.sheet, (x + hdl[0], y + hdl[1], cell[2], cell[3]))

推荐阅读