'Why will my obstacles still spawn next to each other when I coded it so they won't?

I am trying to make it so if my two obstacles spawn near each other they will move, but it won't work. Why?

                if obstacle2.rect.x - obstacle1.rect.x > 0:
                    while obstacle1.rect.x - obstacle2 .rect.x < 100:
                        obstacle1.rect.x = (random.randint(300, 900))
                        obstacle2.rect.x = (random.randint(300, 900))
                if obstacle1.rect.x - obstacle2.rect.x > 0:
                    while obstacle2.rect.x - obstacle1 .rect.x < 100:
                        obstacle1.rect.x = (random.randint(300, 900))
                        obstacle2.rect.x = (random.randint(300, 900))


Solution 1:[1]

The while loops are only checking that the objects overlap in a single direction, when you move them they may overlap in the other direction but the while loop condition is satisfied and exits.

Remove your if statements and create a single while loop that checks if they overlap in either direction

while abs(obstacle1.rect.x - obstacle2.rect.x) < 100:
    obstacle1.rect.x = random.randint(300, 900)
    obstacle2.rect.x = random.randint(300, 900)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Iain Shelvington