2 from plomrogue.errors import ArgError
6 class YX(collections.namedtuple('YX', ('y', 'x'))):
8 def __add__(self, other):
9 return YX(self.y + other.y, self.x + other.x)
11 def __sub__(self, other):
12 return YX(self.y - other.y, self.x - other.x)
15 return 'Y:%s,X:%s' % (self.y, self.x)
21 def __init__(self, size):
24 def get_directions(self):
26 for name in dir(self):
27 if name[:5] == 'move_':
28 directions += [name[5:]]
31 def get_neighbors(self, pos):
33 for direction in self.get_directions():
34 neighbors[direction] = self.move(pos, direction)
37 def move(self, start_pos, direction):
38 mover = getattr(self, 'move_' + direction)
39 target = mover(start_pos)
40 if target.y < 0 or target.x < 0 or \
41 target.y >= self.size.y or target.x >= self.size.x:
47 class MapGeometryWithLeftRightMoves(MapGeometry):
49 def move_LEFT(self, start_pos):
50 return YX(start_pos.y, start_pos.x - 1)
52 def move_RIGHT(self, start_pos):
53 return YX(start_pos.y, start_pos.x + 1)
57 class MapGeometrySquare(MapGeometryWithLeftRightMoves):
59 def move_UP(self, start_pos):
60 return YX(start_pos.y - 1, start_pos.x)
62 def move_DOWN(self, start_pos):
63 return YX(start_pos.y + 1, start_pos.x)
67 class MapGeometryHex(MapGeometryWithLeftRightMoves):
69 def move_UPLEFT(self, start_pos):
70 start_indented = start_pos.y % 2
72 return YX(start_pos.y - 1, start_pos.x)
74 return YX(start_pos.y - 1, start_pos.x - 1)
76 def move_UPRIGHT(self, start_pos):
77 start_indented = start_pos.y % 2
79 return YX(start_pos.y - 1, start_pos.x + 1)
81 return YX(start_pos.y - 1, start_pos.x)
83 def move_DOWNLEFT(self, start_pos):
84 start_indented = start_pos.y % 2
86 return YX(start_pos.y + 1, start_pos.x)
88 return YX(start_pos.y + 1, start_pos.x - 1)
90 def move_DOWNRIGHT(self, start_pos):
91 start_indented = start_pos.y % 2
93 return YX(start_pos.y + 1, start_pos.x + 1)
95 return YX(start_pos.y + 1, start_pos.x)
101 def __init__(self, map_size):
103 self.terrain = '.' * self.size_i
105 def __getitem__(self, yx):
106 return self.terrain[self.get_position_index(yx)]
108 def __setitem__(self, yx, c):
109 pos_i = self.get_position_index(yx)
111 self.terrain = self.terrain[:pos_i] + c + self.terrain[pos_i + 1:]
113 self.terrain[pos_i] = c
117 return self.size.y * self.size.x
119 def set_line(self, y, line):
120 height_map = self.size.y
121 width_map = self.size.x
123 raise ArgError('too large row number %s' % y)
124 width_line = len(line)
125 if width_line != width_map:
126 raise ArgError('map line width %s unequal map width %s' % (width_line, width_map))
127 self.terrain = self.terrain[:y * width_map] + line +\
128 self.terrain[(y + 1) * width_map:]
130 def get_position_index(self, yx):
131 return yx.y * self.size.x + yx.x
135 for y in range(self.size.y):
136 yield (y, self.terrain[y * width:(y + 1) * width])