我有一些代码,当前在屏幕周围的随机点处显示随机数量的随机彩色矩形。现在,我想让它们随机移动。我有一个for循环,用于生成随机的颜色,x,y等,以及正方形移动的方向。在我的代码中,我还有一个for循环(此循环包含在主游戏循环中)显示正方形并解释随机方向,以便它们可以移动。但是,当我尝试运行该程序时,它给了我标题中描述的错误。我究竟做错了什么?

randpop = random.randint(10, 20)

fps = 100

px = random.randint(50, 750)
py = random.randint(50, 750)
pxp = px + 1
pyp = py + 1
pxm = px - 1
pym = py - 1
moves_list = [pxp, pyp, pxm, pym]

population = []
for _ in range(0, randpop):
    pcol = random.choice(colour_list)
    px = random.randint(50, 750)
    py = random.randint(50, 750)
    direction = random.choice(moves_list)
    population.append((px, py, pcol))

[...]

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill(GREY)

    for px, py, pcol, direction in population:
        pygame.draw.rect(screen, pcol, (px, py, 50, 50))

        print(direction)
        if direction == pxp:
            px += 1
        if direction == pyp:
            py += 1
        if direction == pxm:
            px -= 1
        if direction == pym:
            py -= 1

    pygame.display.update()

最佳答案

for循环中,您期望元组大小为4:


  

for px, py, pcol, direction in population:



但是,当您设置元组列表时,您忘记了direction,因此元组大小仅为3。这将导致错误。
direction添加到元组:

population.append((px, py, pcol))

population.append((px, py, pcol, direction))




如果要移动矩形,则必须更新列表中的数据。例如。:

for i, (px, py, pcol, direction) in enumerate(population):

    pygame.draw.rect(screen, pcol, (px, py, 50, 50))

    print(direction)
    if direction == pxp:
        px += 1
    if direction == pyp:
        py += 1
    if direction == pxm:
        px -= 1
    if direction == pym:
        py -= 1

    population[i] = (px, py, pcol, direction)

09-25 19:59