Your application works fine. The issue is, that result of each evaluation of overlap
cause a change of blob_color
. So the last obstacle in the loop "wins". If the last obstacle overlaps
the blob, then the color is orange_blob
, else it is green_blob
.
Set the green color before the loop. If any obstacle overlaps
the blob, then change it to orange. The blob has to be drawn once after the loop. e.g.:
while True:
events()
blob_color = green_blob
for i in range(4):
mx, my = pygame.mouse.get_pos()
offset = (int(mx - ox[i]), int(my - oy[i]))
if obstacle_mask[i].overlap(blob_mask, offset):
blob_color = orange_blob
screen.blit(obstacle[i], (ox[i], oy[i]))
screen.blit(blob_color, (mx, my))
To find obstacle at random positions, which are not overlapping, you have to evaluate if a new obstacle hits any of the former obstacles.
Create a random position:
x, y = random.randint(100, 400), random.randint(100, 400)
And evaluate if there is any obstacle that overlap
s the new position.
isect = any(obstacle_mask[j].overlap(obstacle_mask[i], (x-ox[j], y-oy[j])) for j in range(i))
If that is the case, then repeat the process. Create a new random position and test for overlapping:
obstacle = []
obstacle_mask = []
oy = []
ox = []
for i in range(4):
obstacle.append(pygame.image.load("obstacle-400x399.png").convert_alpha())
obstacle_mask.append(pygame.mask.from_surface(obstacle[i]))
isect = True
while isect:
x, y = random.randint(100, 400), random.randint(100, 400)
isect = any(obstacle_mask[j].overlap(obstacle_mask[i], (x-ox[j], y-oy[j])) for j in range(i))
ox.append(x)
oy.append(y)