如何在无限网格中靠近(0,0)处添加不重叠的新矩形
无限网格中紧邻不重叠矩形放置算法问题
我正在编写一个算法,用于在无限网格中靠近(0,0)的位置放置彼此紧邻但不重叠的矩形。用Pygame做了个快速原型,但效果不理想。每个矩形会预留一个x值作为间距,且矩形只能添加、不能删除。
我尝试了以下代码:
def find_adjacent_position(open_rectangles, all_rectangles, w, h): for existing_rect in open_rectangles: for offset in [(1,0), (-1,0), (0,1), (0,-1)]: x = existing_rect[0] + (existing_rect[2] * offset[0]) + offset[0] y = existing_rect[1] + (existing_rect[3] * offset[1]) + offset[1] if 0 < x + w <= SCREEN_WIDTH // 2 and 0 < y + h <= SCREEN_HEIGHT // 2: new_rect = (x, y, w, h) overlap = any(is_overlap(new_rect, rect) for rect in all_rectangles) if not overlap: open_rectangles.append(new_rect) return new_rect op = 4 for offset in [(1,0), (-1,0), (0,1), (0,-1)]: x = existing_rect[0] + (16 * offset[0]) y = existing_rect[1] + (16 * offset[1]) if 0 < x + offset[0] <= SCREEN_WIDTH // 2 and 0 < y + offset[1] <= SCREEN_HEIGHT // 2: new_rect = (x, y, 16, 16) overlap = any(is_overlap(new_rect, rect) for rect in all_rectangles) if overlap: # 此处无法放置,存在重叠 op -= 1 else: op -= 1 # 超出屏幕范围 if op <= 0: print(f"无处可放,该矩形已标记为封闭 {len(open_rectangles)-1}") open_rectangles.remove(existing_rect) else: print(op) return None
这个函数接收两个列表:
- 所有已放置矩形的列表
- 开放矩形列表:这类矩形的侧边处于“空闲”状态,可以在其旁边放置新矩形
运行后出现的问题:屏幕仍有剩余空间,但矩形无法继续扩展(对应Pygame运行效果:矩形在未填满屏幕时就停止扩展)
以下是间距x为2的手动绘制理想效果示例,涉及的矩形尺寸为(2,4)、(3,4)、(3,3)、(6,3)、(3,5)、(5,4)、(4,9)(顺序仅作示意):
- 红色矩形:“封闭”矩形,无法在其旁放置新矩形
- 蓝色矩形:“开放”矩形,属于open_rectangles列表,可在其旁添加新矩形(对应理想效果:矩形紧凑且合理地填满可用空间)
内容的提问来源于stack exchange,提问作者walksanator
相关产品推荐
相关产品推荐

