How can I randomly place several non-colliding rects?

前端 未结 7 1730
谎友^
谎友^ 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:48

    an alternative pseudocode, to those already mentioned:

    while not enough objects:
      place object randomly
      if overlaps with anything else:
        reduce size until it fits or has zero size
      if zero size: 
        remove
    

    Or something like that.

    But this has the advantage of possibly creating some smaller objects than you intended, and creating objects which almost intersect (i.e. touch).

    If it's a map for the player to traverse, they may still not be able to traverse it because their path could be blocked.

提交回复
热议问题