(IndexError:列表索引超出范围)我的for循环给了我一个错误?

时间:2014-08-21 03:01:20

标签: python for-loop pygame traceback

这是我的代码:

import game, pygame, sys
from gameobjects import *
from imageloader import *




def main():
    screen = pygame.display.set_mode( (800, 600) )
    background = Background("images/Nebula1.bmp", screen.get_width(), screen.get_height())
    letter1 = pygame.image.load("1.bmp")
    letter2 = pygame.image.load("2.bmp")
    letter3 = pygame.image.load("3.bmp")
    letter4 = pygame.image.load("4.bmp")
    letter5 = pygame.image.load("5.bmp")
    letter6 = pygame.image.load("6.bmp")
    letter7 = pygame.image.load("7.bmp")
    letter8 = pygame.image.load("8.bmp")
    letter9 = pygame.image.load("9.bmp")
    letter10 = pygame.image.load("10.bmp")
    Letters = [letter1, letter2, letter3, letter4, letter5, letter6, letter7, letter8, letter9, letter10]
    letter = 0

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        screen.blit(background.image, (0,0))

        for i in Letters:
            screen.blit( Letters[letter], (330 + 14 * letter, 190) )
            letter += 1


        pygame.display.flip()
All the items in the Letters list are pygame.Surfaces retrieved through using pygame.image.load(). Every time I run this code, I get an error that looks like this:

    Traceback (most recent call last):
      File "main.py", line 75, in <module>
        main()
      File "main.py", line 32, in main
        screen.blit( Letters[letter], ((330 + 14 * letter, 190)) )
    IndexError: list index out of range

为什么会这样?这对我来说似乎完全有效。我究竟做错了什么?我想要做的是将屏幕上的每个字母粘贴到最后一个字母上14个像素,因为每个字母的宽度为14个像素。有帮助吗? (我是python的新手,所以如果我犯了一个愚蠢的错误,请原谅我。)

1 个答案:

答案 0 :(得分:2)

您必须为每次迭代设置letter = 0。因为它在while循环之外,所以在初始化时字母只设置为0。之后它会在IndexError的第二次迭代时抛出for i in letters,因为letter因为最后一次迭代而等于letters的长度!

使用enumerate()安全并轻松增加:

for i,val in enumerate(Letters):
        screen.blit( Letters[i], (330 + 14 * letter, 190) )

或者,在while循环中包含letter = 0

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    screen.blit(background.image, (0,0))

    letter = 0
    for i in Letters:
        screen.blit( Letters[i], (330 + 14 * letter, 190) )
        letter += 1