Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - How to position non-overlapping rectangles on a canvas

I have a canvas. On this canvas, I need to position 1, 2 or 3 rectangles. I have to make sure that these rectangles are drawn strictly within the canvas and they're strictly non-overlapping. For the first rectangle, I am picking a random position within the canvas. These rectangles are moved from their top-left corners:

location_x = random.randint(0, (canvas_width - rectangle_width))
location_y = random.randint(0, (canvas_height - rectangle_height))

canvas_width - rectangle_width and canvas_height - rectangle_height ensures that the furthest the rectangle can go is where its edge aligns with the corresponding edge of the canvas.

In these next two lines, I am storing the locations as tuples inside a list:

locations_used.append((location_x, location_y))

In the following two lines, I am picking x and y coordinates within the rectangle by seeing if it is not between the top-left corner and the width/height.

location_x = random.choice(        
            [i for i in range(0, (canvas_width - rectangle_width)) if i not in range(location_x, rectangle_width)]
        )

location_y = random.choice(
            [i for i in range(0, (canvas_height - rectangle_height)) if i not in range(location_y, rectangle_height)]
        )

However, this only makes sure that the rectangle does not overlap with the previous one. It runs the risk where the rectangle could potentially overlap with the first one.

How can I modify the list-comprehension code above to check for every location, width/height range in the list locations_used?

This is the idea:

location_x = random.choice(
            [i for i in range(0, (canvas_width - rectangle_width)) if i not in range(all location_x - rectangle_width)]
        )

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

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...