我正在尝试使角色移动,但是当我走一定距离时,会出现错误

我找不到可行的解决方案,所以我自己尝试了几件事

global walkCount
win.blit(bg, (0, 0))
if walkCount + 1 >= 27:
    walkCount = 0
if left:
    win.blit(walkLeft[walkCount//3], (x, y))
    walkCount += 1
    pygame.display.update()
elif right:
      win.blit(walkRight[walkCount//3], (x,y))
      walkCount += 1
      pygame.display.update()



File "C:\Users\drfur\Desktop\Game\game.py", line 166, in <module>
   rwg()

File "C:\Users\drfur\Desktop\Game\game.py", line 55, in rwg
   win.blit(walkRight[walkcount//3], (x,y))

IndexError: list index out of range



它发生在左右两侧

最佳答案

walkCount的最大值为26。26//3的结果为8。您必须确保列表walkLeftwalkRight具有9个元素。

可以通过计算除以列表长度的除数来避免列表索引超出范围错误。余数可以由模运算符(%)计算。请参见Operators。例如。:

if left:

    i = (walkCount//3) % len(walkLeft)
    win.blit(walkLeft[i], (x, y))

elif right:

    i = (walkCount//3) % len(walkRight)
    win.blit(walkRight[i], (x,y))

walkCount += 1
pygame.display.update()

10-08 18:59