IndexError:列表索引超出范围(Python 2.7)

时间:2013-12-11 07:53:03

标签: python python-2.7 pygame

你好我最近一直在编写一个游戏并且我遇到过并且IndexError说'IndexError:list index out of range'并且想知道是否有人知道为什么?

    class MenuScene(MenuClass):
        def __init__(self, surface, engine):
            MenuClass.__init__(self, surface)

            self.MoonSurvival = engine

            self.currentScene = 0

            self.scenes = ['CARTER?! CARTER?! ARE YOU THERE?!\nYeah I am here',
            'Look there have been sights of hostile alien activity near moon base 4,\n I need you to go and check it out as this could be a problem.\n\nOk I will, where is my rifle?', \
            'It is just outside your room tell,\nme when you are ready and I will send you there.,\nGood luck Carter.\n\nThe aim of the game is to survive the alien invasion as long as possible,\nThere are some special drops the aliens can drop.\nThese include, health, shield, superhealth and triple-bullets.' \
            '\nBe careful Carter. The aliens do not stay small for long....\n',  \
            'CONTROLS:\nA and D = Left, Right\nSPACE = Jump\nLeft Mouse Button = Shoot']



def renderText(self):
            # split texts at \n (newline)

            texts = self.scenes[self.currentScene].split('\n')

            for i in range(len(texts)):
                textSurface = self.menufont.render(texts[i], 0, (255, 0, 0))

                textRect = textSurface.get_rect()
                textRect.centerx = SCREEN_WIDTH / 2
                textRect.centery = SCREEN_HEIGHT / 2 + i * self.menufont.size(texts[i])[1]

                self.surface.blit(textSurface, textRect)

错误出现在代码的渲染文本区域中。这是场景的nextScene函数。

def nextScene(self):
    if self.currentScene < 4:
        # li
        self.currentScene += 1
    elif self.currentScene == 5:
        self.MoonSurvival.resetGame()
        self.MoonSurvival.setState(MENU_GAMEFINISH)
    else:
        self.MoonSurvival.setState(MENU_INGAME)

错误:

Traceback (most recent call last):
  File "F:\My Game\MoonSurvival.py", line 416, in <module>
    Game().run()
  File "F:\My Game\MoonSurvival.py", line 194, in run
    self.menuScene.draw()
  File "F:\My Game\menus.py", line 168, in draw
    self.renderText()
  File "F:\My Game\menus.py", line 202, in renderText
    texts = self.scenes[self.currentScene].split('\n')
IndexError: list index out of range
[Finished in 5.8s]

1 个答案:

答案 0 :(得分:1)

            'It is just outside your room tell,\nme when you are ready and I will send you there.,\nGood luck Carter.\n\nThe aim of the game is to survive the alien invasion as long as possible,\nThere are some special drops the aliens can drop.\nThese include, health, shield, superhealth and triple-bullets.' \

很难看到如此长的一行,但这一行最后没有逗号。当Python看到彼此相邻的两个字符串文字时,它会连接它们的内容并将它们视为一个字符串。输入逗号,看看问题是否消失。我建议在列表的最后一个元素之后添加一个逗号,这样当你以后再添加更多场景时就不会忘记逗号。