5 class YX(collections.namedtuple('YX', ('y', 'x'))):
7 def __add__(self, other):
8 return YX(self.y + other.y, self.x + other.x)
10 def __sub__(self, other):
11 return YX(self.y - other.y, self.x - other.x)
14 return 'Y:%s,X:%s' % (self.y, self.x)
20 def __init__(self, size):
23 def get_directions(self):
25 for name in dir(self):
26 if name[:5] == 'move_':
27 directions += [name[5:]]
30 def move(self, start_pos, direction):
31 mover = getattr(self, 'move_' + direction)
32 target = mover(start_pos)
33 if target.y < 0 or target.x < 0 or \
34 target.y >= self.size.y or target.x >= self.size.x:
40 class MapGeometryWithLeftRightMoves(MapGeometry):
42 def move_LEFT(self, start_pos):
43 return YX(start_pos.y, start_pos.x - 1)
45 def move_RIGHT(self, start_pos):
46 return YX(start_pos.y, start_pos.x + 1)
50 class MapGeometrySquare(MapGeometryWithLeftRightMoves):
52 def move_UP(self, start_pos):
53 return YX(start_pos.y - 1, start_pos.x)
55 def move_DOWN(self, start_pos):
56 return YX(start_pos.y + 1, start_pos.x)
62 def __init__(self, map_size):
64 self.terrain = '.' * self.size_i
66 def __getitem__(self, yx):
67 return self.terrain[self.get_position_index(yx)]
69 def __setitem__(self, yx, c):
70 pos_i = self.get_position_index(yx)
72 self.terrain = self.terrain[:pos_i] + c + self.terrain[pos_i + 1:]
74 self.terrain[pos_i] = c
78 return self.size.y * self.size.x
80 def set_line(self, y, line):
81 height_map = self.size.y
82 width_map = self.size.x
84 raise ArgError('too large row number %s' % y)
85 width_line = len(line)
86 if width_line > width_map:
87 raise ArgError('too large map line width %s' % width_line)
88 self.terrain = self.terrain[:y * width_map] + line +\
89 self.terrain[(y + 1) * width_map:]
91 def get_position_index(self, yx):
92 return yx.y * self.size.x + yx.x
96 for y in range(self.size.y):
97 yield (y, self.terrain[y * width:(y + 1) * width])