Reputation: 47
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
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
Upvotes: 0
Views: 60
Reputation: 2779
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?
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.
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
?
Anyway, why would the lists health
and platforms
be the same size? 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. If that is the idea then to delete an entry from healths
it should not matter which entry from healths
you remove. 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).
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.
Upvotes: 1
Reputation: 434
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]
Upvotes: 1