class PackNode(object): """ Creates an area which can recursively pack smaller areas into itself. """ def __init__(self, xywh): self.rect = Rect(xywh) def __repr__(self): return "<%s %s>" % (self.__class__.__name__, self.rect) def insert(self, xywh): """ Insert an rect into the current rect. Returns a new Node representing the new rect. Returns None if no space is available for the new rect. """ if hasattr(self, 'children'): for child in self.children: r = child.insert(xywh) if r is not None: return r return None rect = Rect(xywh) if self.rect.fits(rect): a = PackNode((self.rect.left+rect.width, self.rect.bottom, self.rect.width-rect.width, rect.height)) b = PackNode((self.rect.left, self.rect.bottom+rect.height, self.rect.width, self.rect.height-rect.height)) self.children = [a,b] return PackNode((self.rect.left, self.rect.bottom, rect.width, rect.height))