ValueError:没有足够的值进行解包(预期值为4,实际值为3)

2024-06-30 11:40:42 发布

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

我有一些代码,目前显示一个随机数随机彩色矩形随机点周围的屏幕。现在,我想让它们随机移动。我有一个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()

Tags: pyforifrandompygamelistpopulationpyp
2条回答

这一行是问题的原因:

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

如果你先看一下,这才是真正的问题:

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

我猜您想键入population.append((px, py, pcol, direction))

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

for px, py, pcol, direction in population:

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

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

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

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

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)

相关问题 更多 >