Python for循环不再从0开始

2024-04-20 11:32:59 发布

您现在位置:Python中文网/ 问答频道 /正文

方法mover工作正常,直到列表中的元素按与以前不同的顺序组织。此时在方法mover中,z变量得到4,然后for循环(第39行)从1到4计数,而不是从0到3。你知道我怎么能解决这个问题吗? 如果有人能解决这个问题,我会很高兴的。你知道吗

import sys
import pygame
import random

screenx = 500
screeny = 800

go = True
speed = 0

playerx = 40
playery = 540

#zuerst xanfang dann xende
gap = [200,300,300,400,100,200]

coordx = [0,300,0,400,0,200]
coordy = [-250,-250,-250,-250,-250,-250]
length = [120,120,120,120,120,120]
width = [200,200,300,100,100,300]

loops = 2
z = 2

pygame.init()
screen = pygame.display.set_mode([screenx,screeny])
screen.fill((0,0,0))
clock = pygame.time.Clock()
imgmid = pygame.image.load("figurschwarz.png")

def drawer():
    for i in range(len(coordx)):
        pygame.draw.rect(screen, (230,10,60), (coordx[i],coordy[i],width[i],length[i]), 0)

def mover():
    global z,coordy
    if loops % 250 == 0 and z<len(coordx)-1:
        z = z+2
    for x in range(0,z):
        print (x)
        if coordy[x] <= screeny+10:
            coordy[x] += 2  
        else:
            z -= 2
            print ("pop")
            for s in range(2):
                for f in range(z):
                    print(f)
                    coordy[f] = coordy[f+1]
                print (coordy)
            coordy.pop(z+1)
            coordy.pop(z)
            print (coordy)



def collisiondetection():
    global go
    #player on the left or right wall
    if playerx <= 0 or playerx+40 >= screenx:
        go = False


while go == True:
    loops += 1
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                speed = -2
            if event.key == pygame.K_RIGHT:
                speed = 2
    screen.fill((0,0,0))
    playerx += speed
    screen.blit(imgmid, (playerx,playery))
    mover()
    drawer()
    collisiondetection()
    pygame.display.flip()
    clock.tick(110)

print ("Dein Score ist " + str(loops))

Tags: ineventgoforifrangescreenpygame
1条回答
网友
1楼 · 发布于 2024-04-20 11:32:59

如果在xfor循环之前再放一个print

def mover():
global z,coordy
if loops % 250 == 0 and z<len(coordx)-1:
    print("loops = ".format(loops))
    z = z+2
print("range(0,z) = {}".format(range(0,z))) #<  Put this for debugging
for x in range(0,z):
    print ("x = {}".format(x))
    if coordy[x] <= screeny+10:  #<      Problem is here
        coordy[x] += 2  
    else:
        ...do something...

您将在索引错误之前获得以下输出:

enter image description here

您可以看到循环实际上是从0开始计数的,但是if条件不满足,因此它在else条件内打印'pop'。之后,它打印另一个x。因为上一个值是0,所以这次它打印1。你认为这里的x以1开头,这是不正确的。你知道吗

索引错误的真正原因是在从coordy列表中弹出最后2个值之后,coordy列表的长度只有4。但是,x的范围是从0到5。所以当x=4时,您的coordy[4]试图从列表中获取不存在的第5个元素。这就是为什么会出现索引错误。你知道吗

相关问题 更多 >