微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

player_image = image_list [self.anim_index] IndexError:列表索引超出范围

如何解决player_image = image_list [self.anim_index] IndexError:列表索引超出范围

因此,每次我运行游戏时,都会出现此错误,自从我将播放动画放给播放器以来,就一直在发生这种错误。我一直在尝试修复它,但是我不知道如何解决它,我试图告诉我的代码何时运行某个部分,但是那不起作用,我也试图将代码移至其他地方,但这是行不通的。 >

我的错误在哪里

if self.anim_index >= len( image_list ):
    self.anim_index = 0

我的完整代码

import pygame
pygame.init()

window = pygame.display.set_mode((700,500))
pygame.display.set_caption("Noobs First Game")


move = pygame.image.load("WASD.png")


# Playerman
class Player:
    def __init__(self,x,y,width,height,color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.speed = 5
        self.isJump = False
        self.JumpCount = 10
        self.idle =[pygame.image.load("player_idel_1.png"),pygame.image.load("player_idel_2.png"),pygame.image.load("player_idel_3.png"),pygame.image.load("player_idel_4.png"),pygame.image.load("player_idel_5.png"),pygame.image.load("player_idel_6.png"),pygame.image.load("player_idel_7.png"),pygame.image.load("player_idel_8.png")
                            ]
        self.right = [pygame.image.load("Player_walk_right1.png"),pygame.image.load("Player_walk_right2.png"),pygame.image.load("Player_walk_right3.png")]

        self.fall = 0
        self.rect = pygame.Rect(x,width)
        self.idle = [pygame.transform.scale(image,(image.get_width()*2,image.get_height()*2)) for image in self.idle]
        self.right = [pygame.transform.scale(image,image.get_height()*2)) for image in self.right]
        self.fps = 10
        self.clock = pygame.time.Clock()
        self.anim_index = 0
        self.direction = "idle"
        self.direction = "right"
        self.next_frame_time = 0
        self.imager_list = self.right
    def get_rect(self):
        self.rect.topleft = (self.x,self.y)
        return self.rect
        pygame.draw.rect(self.color,self.rect)
    
    def draw(self):
        if self.direction == "idle":
            image_list = self.idle
        if self.direction == "right":
            image_list = self.right
         

        # Is it time to show the next animation frame?
        time_Now = pygame.time.get_ticks()
        if ( time_Now > self.next_frame_time ):
            # set the time for the next animation-frame
            inter_frame_delay = 1000 // self.fps   
            self.next_frame_time = time_Now + inter_frame_delay  # in the future
            # move the current image to the next (with wrap-around)
            if image_list == self.idle:
                self.anim_index += 1
                if self.anim_index >= len( image_list ):
                    self.anim_index = 0

        pygame.draw.rect( window,self.color,self.get_rect() )
        player_image = image_list[self.anim_index]

        player_rect = player_image.get_rect(center = self.get_rect().center)
        player_rect.centerx += 3
        player_rect.centery -= 13
        window.blit(player_image,player_rect)
        


class Platform:
    def __init__(self,color):
        self.x = x
        self.y =y
        self. width = width
        self.color = color
        self.height = height
        self.color = color
        self.speed = 4
        self.rect = pygame.Rect(x,height)
    def get_rect(self):
        self.rect.topleft = (self.x,self.y)
        return self.rect
    def draw(self):
        pygame.draw.rect(window,self.get_rect())


class Rule:
    def __init__(self,height)
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window,self.rect)


# Colors for hitBox
white = (255,255,255)
green = (0,0)

# Drawing Player
playerman = Player(350,445,40,white)

#Drawing Platforms
platform1 = Platform(300,-9.1,500,green)
platform2 = Platform(330,451,2000,green)
platform3 = Platform(2300,green)

# Drawing Rule
rule1 = Rule(340,220,green)
rule2 = Rule(20000,-9,1,5,green)

# List
platforms = [platform1,platform2,platform3]

rules = [rule1,rule2]


# draws map
platformGroup = pygame.sprite.Group
Level = [
"                                         1   1","                                         1    ","                         1  1        111 1    ","                         1  1       111  1    ","                         11 1      1111 11    ","                         1  1     11111  1    ","                         1  1    1111111 1    ","           1   1   111   1 11   1111111  1    ","           1   1  11111     1  11111111          ",]

for iy,row in enumerate(Level):
    for ix,col in enumerate(row):
        if col == "1":
            new_platforms = Platform(ix*50,iy*50.2,50,(255,255))
            platforms.append(new_platforms)
    
            

# Windows color
def redrawwindow():
    window.fill((0,0))

    # Drawing the player and other stuff to the screen
    playerman.draw()

    for Platform in platforms:
        Platform.draw()
    for Rule in rules:
        Rule.draw()

x = 10
y = 10
x_change = 0
y_change = 0
old_x = x
old_y = y
fps = (30)
clock = pygame.time.Clock()

run = True
while run:
    clock.tick(fps)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    


    if playerman.y < 250:
        playerman.y += 1
        for Platform in platforms:
            Platform.y += playerman.speed

    if playerman.y > 410:
        playerman.y -= playerman.fall
        for Platform in platforms:
            Platform.y -= playerman.fall

    
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_d:
            x_change = -7
        if event.key == pygame.K_a:
            x_change = 7

    if event.type == pygame.KEYUP:
        if event.key == pygame.K_d or event.key == pygame.K_a:
            x_change = 0

        x += x_change
        if x > 500 - playerman.width or x < 0:
            x = old_x
           
        # lets player move
    keys = pygame.key.get_pressed()
    px,py = playerman.x,playerman.y


    if keys[pygame.K_d]:
        for Platform in platforms:
            Platform.x -= playerman.speed
        for Rule in rules:
            Rule.x -= playerman.speed

    if keys[pygame.K_d]:
        playerman.direction = "right"
    else:
        playerman.direction = "idle"

        
 

    if keys[pygame.K_a]:
        for Platform in platforms:
            Platform.x += playerman.speed
        for Rule in rules:
            Rule.x += playerman.speed



    platform_rect_list = [p.rect for p in platforms]
    player_rect = playerman.get_rect()
    player_rect.topleft = (px,py)

    playerman.y = py
    if player_rect.collidelist(platform_rect_list) < 0:
        playerman.x = px

    move_right = keys[pygame.K_d]
    move_left = keys[pygame.K_a]
    if move_right: 
        for Platform in platforms:
            Platform.x -= playerman.speed
        for Rule in rules:
            Rule.x -= playerman.speed     # <---
    if move_left:
        for Platform in platforms:
            Platform.x += playerman.speed
        for Rule in rules:
            Rule.x += playerman.speed     # <---

    platform_rect_list = [p.get_rect() for p in platforms] # get_rect()
    player_rect = playerman.get_rect()
    player_rect.topleft = (px,py)

    playerman.y = py
    cI = player_rect.collidelist(platform_rect_list)
    if cI >= 0:
        # undo movement of platforms dependent on the direction and intersection distance
        dx = 0
        if move_right: 
            dx = platform_rect_list[cI].left - player_rect.right
        if move_left:
            dx = platform_rect_list[cI].right - player_rect.left
        for Platform in platforms:
            Platform.x -= dx
            Platform.get_rect() # update rectangle
        for Rule in rules:
            Rule.x -= dx             # <---

##############                
  
    # About isJump
    if not playerman.isJump:
        playerman.y += playerman.fall
        playerman.fall += 1
        playerman.isJump = False

        # this part lets you jump on platform only the top 
        collide = False
        for Platform in platforms:
            if playerman.get_rect().colliderect(Platform.rect):
                collide = True
                playerman.isJump = False
                playerman.y = Platform.rect.top - playerman.height
                if playerman.rect.right > Platform.rect.left and playerman.rect.left < Platform.rect.left - playerman.width:
                    playerman.x = Platform.rect.left - playerman.width
                if playerman.rect.left < Platform.rect.right and playerman.rect.right > Platform.rect.right + playerman.width:
                    playerman.x = Platform.rect.right
                       
            # colliding with floor      
            if playerman.rect.bottom >= 500:
                collide = True
                playerman.isJump = False
                playerman.Jumpcount = 10
                playerman.y = 500 - playerman.height

        # Jumping
        if collide:
            if keys[pygame.K_SPACE]:
                playerman.isJump = True
                py -= playerman.speed
            playerman.fall = 0

    # Jump Count

    else:
        if playerman.JumpCount >= 0:
            playerman.y -= (playerman.JumpCount*abs(playerman.JumpCount))*0.3
            playerman.JumpCount -= 1
        else:
            playerman.isJump = False
            playerman.JumpCount = 10

    redrawwindow()
    if playerman.rect.colliderect(rule1.rect):
        window.blit(move,(-40,-100))
    
    pygame.display.update()
pygame.quit()

解决方法

image_listself.idleself.right。这些列表的长度不同。因此,您无需在增加索引后检查索引,而需要在访问列表之前检查索引:

class Player:
    # [...]

    def draw(self):
        if self.direction == "idle":
            image_list = self.idle
        if self.direction == "right":
            image_list = self.right

        # [...]

        if ( time_now > self.next_frame_time ):
            # [...]

            if image_list == self.idle:
                self.anim_index += 1

        # [...]

        if self.anim_index >= len(image_list):
            self.anim_index = 0
        player_image = image_list[self.anim_index]

当您确认self.anim_index小于较长列表(self.idle)的长度时,将发生错误。在下一帧中,image_list可能已切换到较短的列表(self.right)。现在self.anim_index大于列表的长度,就会发生错误。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。