Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

python - Line 51: TypeError: list indices must be integers, not float what is wrong plz help me

The Line . . .. if self.collide(state.platform_list[plat_index]): is giving me an error FLOAT and IDK how to fix it

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()
question from:https://stackoverflow.com/questions/66066145/line-51-typeerror-list-indices-must-be-integers-not-float-what-is-wrong-plz-h

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That line is giving you the error because plat_index is actually a float. Assuming your capitalized constants are integers, self.pos[1] must be a float. You'll have to look farther back in your code to see how that number was generated. As a short-term workaround, just use int():

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

Or, you could call int() on the whole thing, just to be sure:

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

Also, as a side note, the line timer+1 doesn't actually do anything, because it doesn't store the resulting value anywhere.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...