2 # vi: set softtabstop=4 shiftwidth=4 tabstop=8 expandtab:
4 class Rectangle(object):
5 def __init__(self
, x
, y
, w
, h
):
11 def __eq__(self
, other
):
14 if not isinstance(other
, Rectangle
):
16 return (self
.x
== other
.x
and self
.y
== other
.y
17 and self
.width
== other
.width
and self
.height
== other
.height
)
20 return "(%d,%d) [%dx%d]" % (self
.x
, self
.y
, self
.width
, self
.height
)
23 return "Rectangle(%d,%d, %d,%d)" % (
24 self
.x
, self
.y
, self
.width
, self
.height
)
27 class PolyRect(object):
28 def __init__(self
, rects
):
32 return sum([a
.width
* a
.height
for a
in self
.rects
])
34 def subtract(self
, r
):
35 """Subtracts one rectangle from the list."""
39 inter
= intersection(i
, r
)
43 # Create one rectangle above, one below, one left, one right.
45 newrects
.append(Rectangle(i
.x
, i
.y
, i
.width
, inter
.y
- i
.y
))
46 if i
.y
+ i
.height
> inter
.y
+ inter
.height
:
47 y
= inter
.y
+ inter
.height
48 newrects
.append(Rectangle(i
.x
, y
,
49 i
.width
, i
.height
- (y
- i
.y
)))
54 height
= min(i
.y
+ i
.height
, inter
.y
+ inter
.height
) - y
55 newrects
.append(Rectangle(x
, y
, width
, height
))
57 if i
.x
+ i
.width
> inter
.x
+ inter
.width
:
58 x
= inter
.x
+ inter
.width
60 width
= i
.width
- (x
- i
.x
)
61 height
= min(i
.y
+ i
.height
, inter
.y
+ inter
.height
) - y
62 newrects
.append(Rectangle(x
, y
, width
, height
))
64 return PolyRect(newrects
)
66 def intersection(r1
, r2
):
68 width
= min(r1
.width
- (x
- r1
.x
), r2
.width
- (x
- r2
.x
))
70 height
= min(r1
.height
- (y
- r1
.y
), r2
.height
- (y
- r2
.y
))
72 if width
<= 0 or height
<= 0:
74 return Rectangle(x
, y
, width
, height
)