Points & Rectangles
A pair of classes to provide points and rectangles.
Surprisingly, I haven't been able to find a single Python module providing such primitive support.
WxPython supports wxPoint and wxRect, but it lacks many basic functions (such as, say, adding two points together to produce a third point..!)
This code is lacking a zillion essential features (such as "Length"). I only put in the ones I needed immediately. Please add, refactor, optimize, rename stuff to be more standard, etc., as you see fit..!
If there's an actual, accessible, easy-to-include Python module, not tied to a graphics library, that does this stuff already, please write about it here! No sense in reinventing the wheel. I've looked, but haven't found one. Hence this.
1 """
2 Public domain. Do whatever you like with this.
3 """
4 def normalize( x1,y1,x2,y2 ):
5 return (min(x1,x2),min(y1,y2),max(x1,x2),max(y1,y2))
6
7 class Point:
8 def __init__( self, x,y ):
9 self.x = x
10 self.y = y
11 def __add__( self, other ):
12 return Point( self.x+other.x, self.y+other.y )
13 def __sub__( self, other ):
14 return Point( self.x-other.x, self.y-other.y )
15 def __mul__( self, scalar ):
16 return Point( self.x*scalar, self.y*scalar )
17 def __div__( self, scalar ):
18 return Point( self.x/scalar, self.y/scalar )
19 def __str__( self ):
20 return "(%s,%s)" % (self.x,self.y)
21 def XY( self ):
22 return self.x,self.y
23 def Clone( self ):
24 return Point( self.x, self.y )
25 def Integerize( self ):
26 self.x = int( self.x )
27 self.y = int( self.y )
28 def Floatize( self ):
29 self.x = float( self.x )
30 self.y = float( self.y )
31
32 class Rect:
33 def __init__( self, pt1,pt2 ):
34 self.Set( pt1,pt2 )
35 def Contains( self, pt ):
36 x,y = pt.XY()
37 if (x >= self.left and
38 x <= self.right and
39 y >= self.top and
40 y <= self.bottom ):
41 return 1
42 return 0
43 def Set( self, pt1, pt2 ):
44 l,t,r,b = normalize( pt1.x, pt1.y, pt2.x, pt2.y )
45 self.left = l
46 self.top = t
47 self.right = r
48 self.bottom = b
49 def Overlaps( self, other ):
50 return (self.right>other.left) and (self.top < other.bottom) and (self.left<other.right) and (self.bottom>other.top)
51 def GetTL( self ):
52 return Point( self.left, self.top )
53 def GetBR( self ):
54 return Point( self.right, self.bottom )
55 def ExpandedBy( self, n ):
56 p1 = Point( self.left-1, self.top+1 )
57 p2 = Point( self.right+1, self.bottom+1 )
58 return Rect( p1, p2 )
59 def TransformedByFunction( self, foo ):
60 p1 = Point( self.left, self.top )
61 p2 = Point( self.right, self.bottom )
62 p1 = foo( p1 )
63 p2 = foo( p2 )
64 return Rect p1, p2 )
65 def __str__( self ):
66 return "<Rect (%s,%s)-(%s,%s)>" % (self.left,self.top,
67 self.right,self.bottom)