How can I randomly place several non-colliding rects?

前端 未结 7 1712
谎友^
谎友^ 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条回答
  •  旧时难觅i
    2020-12-31 17:30

    There is a very simple approximation to your problem which worked fine for me:

    • Define a grid. For instance a 100 pixel grid writes (x,y) -> (int(x/100),int(y/100)). The grid elements do not overlap.
    • Either put each object in a different grid (randomly inside the grid will look prettier), either put randomly a few objects in each grid, if you can allow a few objects to overlap.

    I used this to randomly generate a 2D map (Zelda like). My objects' images are smaller than <100*100>, so I used grid of size <500*500> and allowed for 1-6 objects in each grid.

提交回复
热议问题