簡體   English   中英

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

[英]IndexError: list index out of range (Python 2.7)

您好,我最近一直在編寫游戲,但遇到IndexError說“ IndexError:列表索引超出范圍”,並想知道是否有人知道為什么?

    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]
            '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看到兩個字符串文字彼此相鄰時,它將它們的內容串聯起來,並將它們視為一個字符串。 放入逗號,看看問題是否消失。 我建議也將逗號放在列表的最后一個元素之后,這樣以后再添加更多場景時就不要忘記逗號。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM