IndexError: list index out of range解决方法

    def display(self):
        if self.hit == True:
            self.screen.blit(self.bomb_list[self.image_index], (self.x, self.y))
            self.image_num += 1
            if self.image_num > 7:
                self.image_num = 0
                self.image_index +=1
            elif self.image_index > 3:#出错位置
                time.sleep(1)
                exit()
                self.image_index = 0
        else:
            self.screen.blit(self.image, (self.x, self.y))

编写飞机大战时添加爆炸效果图片时出错

Traceback (most recent call last):
  File "C:/Users/Lee/PycharmProjects/untitled9/test.py", line 184, in 
    main()
  File "C:/Users/Lee/PycharmProjects/untitled9/test.py", line 175, in main
    hero.display()
  File "C:/Users/Lee/PycharmProjects/untitled9/test.py", line 47, in display
    self.screen.blit(self.bomb_list[self.image_index], (self.x, self.y))
IndexError: list index out of range

查了资料以为是list[0]出错,但无论修改上限和下限都有问题

最后发现是逻辑错误,将elif改为if即可,是一个单独的判断语句,没有连带关系

def display(self):
    if self.hit == True:
        self.screen.blit(self.bomb_list[self.image_index], (self.x, self.y))
        self.image_num += 1
        if self.image_num > 7:
            self.image_num = 0
            self.image_index +=1
        if self.image_index > 3:
            time.sleep(1)
            exit()
            self.image_index = 0
    else:
        self.screen.blit(self.image, (self.x, self.y))

你可能感兴趣的:(python)