IndexError:列表索引超出范围,动画精灵,角色移动

时间:2019-09-13 00:39:14

标签: python pygame

im是python的新手,最近在尝试为我的主要角色的Sprite动画时遇到问题。 代码错误是

  

“ IndexError:列表索引超出范围”。

角色移动几个像素然后停止,并显示错误,它从不显示任何动画。

import pygame
import sys
import os

pygame.display.set_mode()

class Adventurer(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.movex = 0
        self.movey = 0
        self.frame = 0

        self.runRight = []
        for i in range(1,6):
            img = pygame.image.load(os.path.join("Characters", "ADVENTURER", "runR" + str(i) + '.png'))
            img.convert_alpha()
            img.set_colorkey(ALPHA)
        self.runRight.append(img)
        self.image = self.runRight[0]
        self.rect = self.image.get_rect()
        #runningLeft
        self.runLeft = []
        for i in range(1,6):
            img = pygame.image.load(os.path.join("Characters", "ADVENTURER", "runL" + str(i) + '.png'))
            img.convert_alpha()
            img.set_colorkey(ALPHA)
        self.runLeft.append(img)
        self.image = self.runLeft[0]
        self.rect = self.image.get_rect()

    def control(self,x,y): #control player movement
        self.movex += x
        self.movey += y

    def update(self):
        self.rect.x = self.rect.x + self.movex
        self.rect.y = self.rect.y + self.movey

        #moving left
        if self.movex < 0:
            self.frame += 1
            if self.frame > 6*ani:
                self.frame = 0
            self.image = self.runLeft[self.frame//ani]    

        #moving right
        if self.movex > 0:
            self.frame += 1
            if self.frame > 6*ani:
                self.frame = 0
            self.image = self.runRight[self.frame//ani]    


ALPHA = (1, 1, 1)

screenWidth = 900
screenHeight = 507

fps = 20
ani = 6
clock = pygame.time.Clock()
pygame.init()

world = pygame.display.set_mode([screenWidth, screenHeight])
backdrop = pygame.image.load(os.path.join("Backgrounds", "Background1.jpg")).convert()
backdropbox = world.get_rect()

player = Adventurer()
player.rect.x = 0
player.rect.y = 435
player_list = pygame.sprite.Group()
player_list.add(player)
steps = 10 #pixels to move

main = True

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

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                pygame.quit()
                sys.exit()
                main = False
            if event.key == pygame.K_LEFT or event.key == ord("a"):
                player.control(-steps,0)
            if event.key == pygame.K_RIGHT or event.key == ord("d"):
                player.control(steps, 0)
            if event.key == pygame.K_UP or event.key == ord("w"):
                print ("jump")    

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == ord("a"):
                player.control(steps,0)
            if event.key == pygame.K_RIGHT or event.key == ord("d"):
                player.control(-steps,0)
            if event.key == pygame.K_UP or event.key == ord("w"):
                print ("jump stop")



    world.blit(backdrop, backdropbox)
    player.update()
    player_list.draw(world)
    pygame.display.flip()
    clock.tick(fps)

这个主意是为了让角色为运动主意加油。 这是我得到的错误:

FromScratch.py", line 51, in update self.image = self.runLeft[self.frame//ani]
    IndexError: list index out of range

2 个答案:

答案 0 :(得分:1)

在您的代码中,仅将最后一个图像追加到列表中,因为npm run myscript -- --foo=1 --bar=2 指令位于循环之后。它必须在循环中完成:

.append
self.runRight = []
for i in range(1,6):
    img = pygame.image.load(os.path.join("Characters", "ADVENTURER", "runR" + str(i) + '.png'))
    img.convert_alpha()
    img.set_colorkey(ALPHA)
    # -->
    self.runRight.append(img)

“列表索引超出范围” 超出范围错误是由查找图像列表引起的。您必须使用模(self.runLeft = [] for i in range(1,6): img = pygame.image.load(os.path.join("Characters", "ADVENTURER", "runL" + str(i) + '.png')) img.convert_alpha() img.set_colorkey(ALPHA) # --> self.runLeft.append(img) )运算符,才能计算除以图像数量的整数余数(请参见operator):

%

根据评论:

  

[...]移动非常快[...]

在初始化时添加def update(self): # [...] if self.movex < 0: self.frame += 1 self.image = self.runLeft[(self.frame//ani) % len(self.runLeft)] if self.movex > 0: self.frame += 1 self.image = self.runRight[(self.frame//ani) % len(self.runRight)] ,并在游戏循环内添加clock = pygame.time.Clock()(在clock.tick(60)之后)。参见pygame.time.Clock。使用.tick()的参数,您可以限制速度:

while main == True:

答案 1 :(得分:0)

self.runLeft.append(img)的用意太少,将其置于for循环之外。因此,仅将最后一个图像添加到self.runLeft中,因此尝试访问列表的第二到第五个元素(当self.frame大于ani时)会产生错误,而不是产生动画。