How can I randomly place several non-colliding rects?

前端 未结 7 1710
谎友^
谎友^ 2020-12-31 16:55

I\'m working on some 2D games with Pygame. I need to place several objects at the same time randomly without them intersecting. I have tried a few obvious

7条回答
  •  既然无缘
    2020-12-31 17:37

    In my case I had a similar problem except that I had some pre-exiting rectangles inside the overall rectangle. So new rectangles had to be placed around those existing ones.

    I used a greedy approach:

    • Rectangularize the overall (global) rectangle: create a grid from the sorted x & sorted y coordinates of all rectangles so far. So that will give you an irregular (but rectangular) grid.
    • For each grid cell calculate the area, this gives you a matrix of areas.
    • Use Kadanes 2D algorithm to find the sub matrix that gives you the maximum area (= the largest free rectangle)
    • Place a random rectangle in that free space
    • Repeat

    This requires a conversion from your original coordinate space to/from the grid space but straightforward to do.

    (Note that running Kadene directly on the original, global rectangle takes to long. Going via a grid approximation is plenty fast for my application)

提交回复
热议问题