【问题标题】:ValueError: not enough values to unpack (expected 4, got 3)ValueError:没有足够的值来解包(预期 4,得到 3)
【发布时间】:2019-07-28 15:27:35
【问题描述】:

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

【问题讨论】:

  • 哪一行给出了错误?什么是堆栈跟踪?

标签: python pygame


【解决方案1】:

for-loop 中,您希望元组大小为 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)

【讨论】:

  • 谢谢!这确实使程序正常运行,并且错误消失了。但是,现在它只运行了几秒钟,然后出现此错误并停止:for px, py, pcol, direction in population: TypeError: cannot unpack non-iterable int object
  • @DuckMcFuddle 抱歉,我无法重现此内容。请注意,矩形离开屏幕,但继续移动。我建议实现一个游戏逻辑来处理它。
  • 哎呀,我在你的代码中遗漏了一些东西。它现在运行良好,我什至实现了一些防止矩形飞出屏幕的代码。谢谢!
【解决方案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))

【讨论】:

    猜你喜欢
    • 2016-07-05
    • 1970-01-01
    • 2017-09-14
    • 2022-01-21
    • 2017-07-04
    • 2020-07-17
    • 1970-01-01
    • 2019-01-05
    • 2019-02-08
    相关资源
    最近更新 更多