Reputation: 27
I've got some code that currently displays a random number of randomly coloured rectangles at random points around the screen. Now, I want to make them move randomly. I have a for loop that is generating the random colours, x, y, etc. and also the direction that the squares will move in. Further down in my code, I have another for loop (this one contained within the main game loop) that displays the squares and interprets the random direction so they can move. However, when I try to run the program, it gives me the error described in the title. What am I doing wrong?
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()
Upvotes: 1
Views: 5727
Reputation: 210909
In the for
-loop you expect that the tuple size is 4:
for px, py, pcol, direction in population:
But when you set up the list of tuples, then you have forgotten direction
, so the tuple size is just 3. This causes the error.
Add direction
to the tuple:
population.append((px, py, pcol))
population.append((px, py, pcol, direction))
If you want to make the rectangles move, then you've to update the data in the list. 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)
Upvotes: 1
Reputation: 1
This line is the cause of the issue:
for px, py, pcol, direction in population:
pygame.draw.rect(screen, pcol, (px, py, 50, 50))
And if you look before that, this is actually the real problem:
population.append((px, py, pcol))
I assume you wanted to type population.append((px, py, pcol, direction))
Upvotes: 0