首页 > 解决方案 > 第 51 行:TypeError:列表索引必须是整数,而不是浮点数有什么问题请帮助我

问题描述

线。. .. if self.collide(state.platform_list[plat_index]): 给我一个错误 FLOAT 和 IDK 如何解决它

def update (self, state):
    global timer
    timer+1
    self.pos[0] = (self.pos[0] + self.vel[0]) % CANVAS_WIDTH
    plat_index = min(self.pos[1] // PLATFORM_SPACING, NUM_PLAT - 1)
    if self.collide(state.platform_list[plat_index]):           
        BOUNCE_SOUND.play()
        self.vel[1] = max(-self.vel[1], REBOUND_VELOCITY)
        if random.random()> .678:   
            state.platform_list[plat_index].remove()
    else:
        self.pos[1] += self.vel[1]
        self.vel[1] -= .1
        if self.pos[1] - state.camera_pos[1] > CANVAS_HEIGHT - CLEARANCE:
            state.camera_pos[1] = self.pos[1] - (CANVAS_HEIGHT - CLEARANCE)
        if self.pos[1] - state.camera_pos[1] < -50:
            finish_time = time.time()
            state.start_game()

标签: pythonpython-3.x

解决方案


那条线给你错误,因为plat_index它实际上是一个浮点数。假设您的大写常量是整数,则self.pos[1]必须是浮点数。您必须更深入地查看您的代码以查看该数字是如何生成的。作为短期解决方法,只需使用int()

plat_index = min(int(self.pos[1]) // PLATFORM_SPACING, NUM_PLAT - 1)

或者,您可以调用int()整个过程,以确保:

plat_index = int(min(self.pos[1] // PLATFORM_SPACING, NUM_PLAT - 1))

另外,作为旁注,该行timer+1实际上并没有做任何事情,因为它不会将结果值存储在任何地方。


推荐阅读