mercredi 27 janvier 2021

Generating 3 random tuples within specified ranges

My goal is to generate locations for where I will be drawing rectangular images on a canvas. I want to generate 3 locations that will stay within the canvas while preventing overlap-. This is my approach:

for i in range(0, len(logos)):

    # Opens the first logo in the random sample as a PIL image
    logo = Image.open(current_dir + '/Logos/' + logos[i], 'r').convert('RGBA')
    logos_used.append(logos[i]) # Adds the current logo inside logos_used

    logo_width, logo_height = logo.size  # Gets the dimensions of the current augmented logo

    # A random position for the 1st logo
    logo_location_x, logo_location_y = logo_position(canvas_width, canvas_height, logo_width, logo_height)
    locations_used.append((logo_location_x, logo_location_y))

    # Working to generate positions for the logos. The logic inside this while loop is incomplete.
    # Because I already have 1 location tuple saved, I now have to get n-1 locations more.
    while len(locations_used) < n-1:
        # Here, I am generating random locations
        logo_location_x = random.randint(0, canvas_width - logo_width)
        logo_location_y = random.randint(0, canvas_height - logo_height)
        
        # I am traversing through every generated location
        for i in range(0, len(locations_used)):

            # Here, I am checking for overlaps.
            if logo_location_x not in range(locations_used[i][0], logo_width) 
           and logo_location_y not in range(locations_used[i][1], logo_height):
                locations_used.append((logo_location_x, logo_location_y))

    print(locations_used)

The main for loop has more code than what you see. It also takes care of drawing the logos on the canvas one by one. len(logos) is at most 3. I removed most of that code to keep it brief and to the point. My goal, as I said, is to generate 3 locations on the canvas that don't overlap the images.

However, this is my output:

[(45, 14)]
[(45, 14), (467, 401)]
[(596, 638)]
[(596, 638), (127, 50)]
[(396, 419)]
[(396, 419), (709, 173)]
[(370, 42)]
[(370, 42), (570, 95)]
[(25, 124)]
[(25, 124), (765, 189)]
[(631, 544)]
[(631, 544), (430, 445)]
[(1688, 149)]
[(1688, 149), (862, 123)]

The output should be 3 two-tuples of locations on the canvas. Not what I have above.




Aucun commentaire:

Enregistrer un commentaire