Place random non-overlapping rectangles on a panel

后端 未结 5 790
别那么骄傲
别那么骄傲 2020-12-05 11:44

I\'ve a panel of size X by Y. I want to place up to N rectangles, sized randomly, upon this panel, but I don\'t want any of them to overlap. I need to know the X, Y position

相关标签:
5条回答
  • 2020-12-05 11:53

    I would advise you use StaxMans suggestion.

    Here is my 2c:

    Add a whole lot of rectangles randomly (overlapping each other). delete overlapping rectangles:

    for rectangle in list of rectangles:
        if rectangle not deleted:
            delete all rectangles touching rectangle.
    

    to find all the rectangles touching a particular rectangle, you can use a quad tree or inequalities based on x1,y1 x2,y2 values.

    Edit: In fact, most game engines such as pygame etc include collision detection of rectangles which is a common problem.

    0 讨论(0)
  • 2020-12-05 11:55

    I used this Rectangle Packing algorithm in one of my applications, available as C# source files.

    The algorithm is initialized with the size of the panel, then you iterate through all rectangles and get their position. The order of the rectangles may influence the result, depending on the packer.

    0 讨论(0)
  • 2020-12-05 11:59

    You can model this by a set of "free" rectangles, starting with single one with coordinates of 0,0, size (x, y). Each time you need to add one more rectangle, choose one of remaining "free" rectangles, generate new rectangle (with top-left coordinate and size such that it will be fully contained), and split that rectangle as well as any other overlapping "free" rectangle, such that children express remaining free space. This will result in 0 to 4 new rectangles (0 if new rectangle was exactly the size of old free rectangle; 4 if it's in the middle and so on). Over time you will get more and more smaller and smaller free areas, so rectangles you create will be smaller as well.

    Ok, not a very elaborate explanation, it's easier to show on whiteboard. But the model is one I used for finding starting location for newly cut'n pasted gui components; it's easy to keep track of available chunks of screen, and choose (for example) left or topmost such area.

    0 讨论(0)
  • 2020-12-05 12:14

    Here is a decent article on 2d packing algorithms: http://www.devx.com/dotnet/Article/36005

    You'll generally want some sort of algorithm using heuristics to achieve decent results. A simple (but non-optimal) solution would be the first fit algorithm.

    0 讨论(0)
  • 2020-12-05 12:15

    Or maintain a list of rectangles already added and create an algorithm that figures out where to place the new rectangle based on that list. You can create a basic Rectangle class to hold the information about your rectangles.

    Shouldn't be so hard to create a custom algorithm.

    0 讨论(0)
提交回复
热议问题