所以我一直在测试这段代码,我找到了一个关于如何在pygame中添加spritesheets的教程,并决定尝试这个:https://www.spriters-resource.com/3ds/dragonballzextremebutoden/sheet/67257/
我按照视频说的做了并计算了列和行,这是我的代码:
pygame.init()
CLOCK = pygame.time.Clock()
DS = pygame.display.set_mode((W, H))
FPS = 60
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][2], self.cells[cellIndex][3]))
s = spritesheet('Number18.png', 58, 6)
CENTER_HANDLE = 6
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), 20, 10)
DS.blit(bg,(0,0))
pygame.display.update()
CLOCK.tick(FPS)
DS.fill(BLACK)
行s = spritesheet("Number18.png", 58, 6)
的数字58,6基本上是我在这个spritesheet块上计算的行数和列数,但我遇到问题,例如pygame窗口“没有响应”,图像没有加载,我无法移动pygame屏幕。
我遇到了诸如“没有回应”的pygame窗口等问题,[...]
首先,您要做的是将en事件循环添加到应用程序的主循环中。
pygame.event
从队列中删除待处理的事件消息并将其返回。至少你应该处理QUIT
事件。设置主循环False
的控制变量的值:
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
精灵表中的图块大小不同。将cells
列表限制为具有相同大小的表单的某些部分。
请尝试以下方法:
class spritesheet:
def __init__(self, filename, py, tw, th, tiles):
self.sheet = pygame.image.load(filename).convert_alpha()
self.py = py
self.tw = tw
self.th = th
self.totalCellCount = tiles
self.rect = self.sheet.get_rect()
w, h = tw, th
hw, hh = self.cellCenter = (w / 2, h / 2)
self.cells = [(1+i*tw, self.py, tw-1, th-1) for i in range(tiles)]
self.handle = list([
(0,0), (-hw, 0), (-w, 0),
(0, -hh), (-hw, -hh), (-w, -hh),
(0, -h), (-hw, -h), (-w, -h),])
s = spritesheet('Number18.png', 1085, 80, 134, 8)
[...]图像没有加载[...]
确保映像位于应用程序的工作目录中。
如果要绘制spritsheet的子图像,则需要将area
的pygame.Surface.blit
参数(第3个参数)设置为子图像的矩形区域:
def draw(self, surface, cellIndex, x, y, handle = 0):
hdl = self.handle[handle]
surface.blit(self.sheet, (x + hdl[0], y + hdl[1]), area=self.cells[cellIndex])
[...]我无法移动[...]
你必须改变精灵的位置。处理KEYDOWN
事件。存储精灵的位置(px
,py
)。按下K_UP
,K_DOWN
,K_LEFT
或K_RIGHT
键时更改位置:
run = True
px, py, speed = HW, HH, 10
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
py -= speed
elif event.key == pygame.K_DOWN:
py += speed
elif event.key == pygame.K_LEFT:
px -= speed
elif event.key == pygame.K_RIGHT:
px += speed