Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

python - How do I make objects never overlap?

I am trying to make a car game in pygame, but whenever I try to spawn the cars, some of them get on top of each other, how do I fix it?

Here is the code for spawning the car:

        if len(enemiesL) == 0:
            if len(enemiesR) == 0:
                wavelengthL += 3
            for _ in range(wavelengthL):
                enemy = EnemyL(random.randrange(160, Width/2 - 50), random.randrange(-1500, -100), random.choice(["black", "blue", "brown", "darkblue", "orange", "pale", "purple", "red", "white", "yellow"]))
                enemiesL.append(enemy)
        
        if len(enemiesR) == 0:
            wavelengthR += 3
            for _ in range(wavelengthR):
                enemy = EnemyR(random.randrange(Width/2, Width-200), random.randrange(-1500, -100), random.choice(["black", "blue", "brown", "darkblue", "orange", "pale", "purple", "red", "white", "yellow"]))
                enemiesR.append(enemy)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...