简体   繁体   English

“列表分配索引超出范围”错误如何修复?

[英]'list assignment index out of range' Error How To Fix?

so I made this short script where if I collide with a platform it should delete 1 of my health but I am getting this error所以我做了这个简短的脚本,如果我与一个平台发生碰撞,它应该删除我的 1 个健康但我收到了这个错误

VIdeo OF What I am Trying To Say <-- as you can see if I collide with the my ice tiles it should delete one of my players health --我想说什么的视频 <--正如你所看到的,如果我与我的冰块相撞,它应该会删除我的一个玩家健康-

 'list assignment index out of range' 
            for dude in range(len(platforms)-1,-1,-1):
                if playerman.rect.colliderect(platforms[dude].rect):
                    del healths[dude]



my full code cant fit in so I made it a pastebin script我的完整代码不适合,所以我把它做成了一个 pastebin脚本

Check if element is present before deleting it.在删除之前检查元素是否存在。

for dude in range(len(platforms)-1,-1,-1):
    if playerman.rect.colliderect(platforms[dude].rect):
        if dude < len(healths): #Check
            del healths[dude]

it is not entirely clear why yo are going backwards through the platforms instead of forward through the platforms list based on the code here.目前还不完全清楚为什么你要通过平台后退而不是根据此处的代码通过平台列表前进。 Is there more code in that for loop?该 for 循环中是否有更多代码?

Anyway, the range() spec used is going to keep it within the range of the list platforms , so that suggests that it is the list healths that is going out of range.无论如何,使用的 range() 规范会将其保持在列表platforms的范围内,因此这表明超出范围的是列表运行healths

Is health actually a list?健康真的是一个清单吗? That is an odd way to manage/keep track of a players health.这是管理/跟踪玩家健康状况的一种奇怪方式。 You usually just do that with a counter.您通常只需使用计数器即可。 What are healths ?什么是healths

Anyway, why would the lists health and platforms be the same size?无论如何,为什么列表healthplatforms的大小相同? That seems the obvious problem.这似乎是一个明显的问题。 It seems like you are managing health by having a bunch of objects that each represent a unit of health somehow and that to delete a unit of health you delete something of the healths list.似乎您通过拥有一堆对象来管理健康,每个对象以某种方式代表一个健康单位,并且要删除一个健康单位,您会删除healths列表中的某些内容。 If that is the idea then to delete an entry from healths it should not matter which entry from healths you remove.如果这是这样的想法,那么从healths中删除一个条目应该无关紧要从healths中删除哪个条目。 You can just delete the last entry on the list with healths.pop() (which removes the last entry and is the most efficient to delete).您可以使用healths.pop()删除列表中的最后一个条目(删除最后一个条目并且删除效率最高)。

for dude in range(len(platforms)-1,-1,-1):
    if playerman.rect.colliderect(platforms[dude].rect):
        healths.pop()

However this still seems like a very odd way of tracking health.然而,这似乎仍然是一种非常奇怪的追踪健康状况的方式。 I would suggest that you reexamine this.我建议你重新检查一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM