How to prevent two sprites from overlapping after random repositioning?

I’m creating a game in MakeCode Arcade where the player gains points by touching a food sprite and loses lives by touching an enemy sprite.
After the player touches either, both the food and enemy are moved to random positions on the screen.
The problem is that sometimes they end up on top of each other, which makes it too easy to lose a life unintentionally.
I tried solving it with a while loop and overlaps_with() in Python, but MakeCode says the project can’t be converted back to blocks.
What’s the best way to solve this using only blocks?

Hereby attached a screenshot of the blocks so far:

1 Like

I usually use a While loop that checks for overlapping. For example, a While loop that looks something like this:

While < (sprite1 is overlapping sprite2) > {
//randomly set the sprite position
}

Thanks for your reply.
I’ve fixed it this way at the moment.

def on_on_overlap(sprite2, otherSprite2):
    info.change_life_by(-1)
    safe_place_sprites()
sprites.on_overlap(SpriteKind.player, SpriteKind.enemy, on_on_overlap)

def on_on_overlap2(sprite, otherSprite):
    info.change_score_by(1)
    info.start_countdown(3)
    safe_place_sprites()
sprites.on_overlap(SpriteKind.player, SpriteKind.food, on_on_overlap2)

def safe_place_sprites():
    global max_attempts
    max_attempts = 50
    for index in range(max_attempts):
        pizza.set_position(randint(0, scene.screen_width() - pizza.width),
            randint(0, scene.screen_height() - pizza.height))
        eten_vis.set_position(randint(0, scene.screen_width() - eten_vis.width),
            randint(0, scene.screen_height() - eten_vis.height))
        if not (pizza.overlaps_with(eten_vis)) and not (pizza.overlaps_with(mySprite)) and not (eten_vis.overlaps_with(mySprite)):
            break
1 Like