Python for循环不再从0开始

时间:2018-09-22 11:51:21

标签: python pygame

方法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))

1 个答案:

答案 0 :(得分:1)

如果您在print的{​​{1}}循环之前再放置一个for

x

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

enter image description here

您可以看到循环实际上是从0开始计数,但是不满足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... 条件,因此它将在if条件内打印'pop'。之后,它将打印另一个x。由于先前的值是0,所以这次它将打印1。您认为else从1开始,这是不正确的。

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