Create a random position and evaluate if a new car at thai position is overlapping with any other car. If the car is overlapping, then discard the position. Use pygame.Rect
objects and colliderect()
to evaluate if cars are overlapping.
In the following is assumed that the position of a car is (enmey.x
, enemy.y
) and the size of a car is (enemy_width
, enemy_height
):
for _ in range(wavelengthL):
while True:
x, y = random.randrange(160, Width/2 - 50), random.randrange(-1500, -100)
new_rect = pygame.Rect(x, y, enemy_width, enemy_height)
if not any(enmey for enmey in enemiesL if new_rect.colliderect(enmey.x, enmey.y, enemy_width, enemy_height)):
break
enemy = EnemyL(x, y, random.choice(["black", "blue", "brown", "darkblue", "orange", "pale", "purple", "red", "white", "yellow"]))
enemiesL.append(enemy)
for _ in range(wavelengthR):
while True:
x, y = random.randrange(Width/2, Width-200), random.randrange(-1500, -100)
new_rect = pygame.Rect(x, y, enemy_width, enemy_height)
if not any(enmey for enmey in enemiesR if new_rect.colliderect(enmey.x, enmey.y, enemy_width, enemy_height)):
break
enemy = EnemyR(x, y, random.choice(["black", "blue", "brown", "darkblue", "orange", "pale", "purple", "red", "white", "yellow"]))
enemiesR.append(enemy)