![](/img/trans.png)
[英]Python 2 - ValueError: not enough values to unpack (expected 6, got 1)
[英]ValueError: not enough values to unpack (expected 4, got 3)
我有一些代码当前在屏幕周围的随机点显示随机数量的随机彩色矩形。 现在,我想让它们随机移动。 我有一个 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
元组添加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:
pygame.draw.rect(screen, pcol, (px, py, 50, 50))
如果你先看看,这实际上是真正的问题:
population.append((px, py, pcol))
我假设你想输入population.append((px, py, pcol, direction))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.