def split(self, *args): if len(args) == 1: if len(args[0]) != 2: raise ValueError() w, h = args[0] elif len(args) == 2: w, h = args else: raise ValueError("requires width and height") # sentinel if self.occupied(): return None if not self.embrace(w, h): return None if self.fit(w, h): self.occupy() return self # if not splited if self.size == 0: self.left = Node() self.right = Node() self.size += 2 # if self.rect.w - w == self.rect.h - h: # left/right or top/down is ok if self.rect.w - w > self.rect.h - h: # go with left/right self.left.rect = rect.Rect(w, self.rect.h, x=self.rect.x, y=self.rect.y) self.right.rect = rect.Rect(self.rect.w - w, self.rect.h, x=self.rect.x + w, y=self.rect.y) else: # go with top/down self.left.rect = rect.Rect(self.rect.w, h, x=self.rect.x, y=self.rect.y) self.right.rect = rect.Rect(self.rect.w, self.rect.h - h, x=self.rect.x, y=self.rect.y + h) # recursively split it ok = self.left.split(w, h) if not ok: return self.right.split(w, h) else: return ok
def test_one(): r = rect.Rect(30, 40) assert r.x == 0 assert r.y == 0 assert r.w == 30 assert r.h == 40
def test_two(): r = rect.Rect(20, 30, x= 100, y= 50) assert r.x == 100 assert r.y == 50 assert r.w == 20 assert r.h == 30
def test_three(): try: r = rect.Rect(30, x= 100) except: assert True return assert False
def __init__(self, width=None, height=None, parent=None): self.left = None self.right = None self.parent = parent if width and height: self.rect = rect.Rect(width, height) else: self.rect = None self.size = 0