root/trunk/py/ModestMaps/Core.py

Revision 686, 2.3 kB (checked in by migurski, 2 months ago)

Added magic methods to Coordinate so it behaves nicely in sets and sorts

Line 
1 """
2 >>> p = Point(0, 1)
3 >>> p
4 (0.000, 1.000)
5 >>> p.x
6 0
7 >>> p.y
8 1
9
10 >>> c = Coordinate(0, 1, 2)
11 >>> c
12 (0.000, 1.000 @2.000)
13 >>> c.row
14 0
15 >>> c.column
16 1
17 >>> c.zoom
18 2
19 >>> c.zoomTo(3)
20 (0.000, 2.000 @3.000)
21 >>> c.zoomTo(1)
22 (0.000, 0.500 @1.000)
23 >>> c.up()
24 (-1.000, 1.000 @2.000)
25 >>> c.right()
26 (0.000, 2.000 @2.000)
27 >>> c.down()
28 (1.000, 1.000 @2.000)
29 >>> c.left()
30 (0.000, 0.000 @2.000)
31 """
32
33 import math
34
35 class Point:
36     def __init__(self, x, y):
37         self.x = x
38         self.y = y
39    
40     def __repr__(self):
41         return '(%(x).3f, %(y).3f)' % self.__dict__
42    
43 class Coordinate:
44     MAX_ZOOM = 25
45
46     def __init__(self, row, column, zoom):
47         self.row = row
48         self.column = column
49         self.zoom = zoom
50    
51     def __repr__(self):
52         return '(%(row).3f, %(column).3f @%(zoom).3f)' % self.__dict__
53        
54     def __eq__(self, other):
55         return self.zoom == other.zoom and self.row == other.row and self.column == other.column
56        
57     def __cmp__(self, other):
58         return cmp((self.zoom, self.row, self.column), (other.zoom, other.row, other.column))
59
60     def __hash__(self):
61         return hash(('Coordinate', self.row, self.column, self.zoom))
62        
63     def copy(self):
64         return self.__class__(self.row, self.column, self.zoom)
65        
66     def container(self):
67         return self.__class__(math.floor(self.row), math.floor(self.column), self.zoom)
68
69     def zoomTo(self, destination):
70         return self.__class__(self.row * math.pow(2, destination - self.zoom),
71                               self.column * math.pow(2, destination - self.zoom),
72                               destination)
73    
74     def zoomBy(self, distance):
75         return self.__class__(self.row * math.pow(2, distance),
76                               self.column * math.pow(2, distance),
77                               self.zoom + distance)
78
79     def up(self, distance=1):
80         return self.__class__(self.row - distance, self.column, self.zoom)
81
82     def right(self, distance=1):
83         return self.__class__(self.row, self.column + distance, self.zoom)
84
85     def down(self, distance=1):
86         return self.__class__(self.row + distance, self.column, self.zoom)
87
88     def left(self, distance=1):
89         return self.__class__(self.row, self.column - distance, self.zoom)
90
91 if __name__ == '__main__':
92     import doctest
93     doctest.testmod()
Note: See TracBrowser for help on using the browser.