我有一些代码,目前显示一个随机数随机彩色矩形随机点周围的屏幕。现在,我想让它们随机移动。我有一个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()
这一行是问题的原因:
如果你先看一下,这才是真正的问题:
我猜您想键入
population.append((px, py, pcol, direction))
在
for
-循环中,您希望元组大小为4:但是当您设置元组列表时,您已经忘记了
direction
,因此元组大小仅为3。这会导致错误。将
direction
添加到元组:population.append((px, py, pcol))
如果要移动矩形,则必须更新列表中的数据。e、 g.:
相关问题 更多 >
编程相关推荐