我目前正在尝试使用 pygame 开发游戏,但我的一些列表存在一些问题。真的很简单,我希望在离开屏幕时删除镜头。在我拍摄不止一个之前,我当前的代码工作完美。
当前代码:
#ManageShots
for i in range (len(ShotArray)):
ShotArray[i].x += 10
windowSurface.blit(ShotImage, ShotArray[i])
if(ShotArray[i].x > WINDOWWIDTH):
ShotArray.pop(i)
错误信息:
ShotArray[i].x += 10
IndexError: list index out of range
请您参考如下方法:
从列表中弹出一个项目会使该项目之后的所有内容都上移一个位置。因此,您最终得到的索引 i 很容易超出范围。
在循环后从列表中删除项目,或反向循环列表:
for shot in reversed(ShotArray):
shot.x += 10
windowSurface.blit(ShotImage, shot)
if shot.x > WINDOWWIDTH:
ShotArray.remove(shot)
