git @ Cat's Eye Technologies The-Dipple / f7f6220
Add (incorrect, but trying) implementation of orientable grid. catseye 12 years ago
1 changed file(s) with 73 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
0 # A square grid, with rotation. Ostensibly for implementing Nhohnhehr
1 # more efficiently.
2
3 class Room(object):
4 """
5
6 >>> r = Room(3, 0)
7 >>> r.store(0, 0, 'a')
8 >>> r.store(1, 0, 'b')
9 >>> r.store(2, 0, 'c')
10 >>> r.store(0, 1, '-')
11 >>> r.store(0, 2, 'A')
12 >>> r.store(2, 2, 'Z')
13 >>> print r
14 abc
15 -
16 A Z
17
18 >>> r.orientation = 90
19 >>> print r
20 c Z
21 b
22 a-A
23
24 >>> r.orientation = 180
25 >>> print r
26 Z A
27 -
28 cba
29
30 >>> r.orientation = 270
31 >>> print r
32 A-a
33 b
34 Z c
35
36 """
37 def __init__(self, size, orientation):
38 self.size = size
39 self.orientation = orientation
40 self.grid = {}
41
42 def rotate(self, x, y):
43 if self.orientation == 0:
44 return (x, y)
45 elif self.orientation == 90:
46 return (y, (self.size-1) - x)
47 elif self.orientation == 180:
48 return ((self.size-1) - x, y)
49 elif self.orientation == 270:
50 return (y, x)
51 else:
52 raise NotImplementedError("Orientation must be 0, 90, 180, or 270")
53
54 def fetch(self, x, y):
55 return self.grid.setdefault(self.rotate(x, y), ' ')
56
57 def store(self, x, y, c):
58 self.grid[self.rotate(x, y)] = c
59
60 def __str__(self):
61 buf = ''
62 for y in range(0, self.size):
63 line = ''
64 for x in range(0, self.size):
65 line += self.fetch(x, y)
66 buf += line + '\n'
67 return buf.rstrip('\n')
68
69
70 if __name__ == '__main__':
71 import doctest
72 doctest.testmod()