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 self.directions = self.get_directions()
26 def get_directions(self):
29 for name in dir(self):
30 if name[:len(prefix)] == prefix:
31 directions += [name[len(prefix):]]
34 def get_neighbors_yxyx(self, yxyx):
36 for direction in self.directions:
37 neighbors[direction] = self.move_yxyx(yxyx, direction)
40 def get_neighbors_yx(self, pos):
42 for direction in self.directions:
43 neighbors[direction] = self.move_yx(pos, direction)
46 def get_neighbors_i(self, i):
47 if i in self.neighbors_i:
48 return self.neighbors_i[i]
49 pos = YX(i // self.size.x, i % self.size.x)
50 neighbors_pos = self.get_neighbors_yx(pos)
52 for direction in neighbors_pos:
53 pos = neighbors_pos[direction]
55 neighbors_i[direction] = None
57 neighbors_i[direction] = pos.y * self.size.x + pos.x
58 self.neighbors_i[i] = neighbors_i
59 return self.neighbors_i[i]
61 def move_yx(self, start_yx, direction, check=True):
62 mover = getattr(self, 'move__' + direction)
63 target = mover(start_yx)
64 # TODO refactor with SourcedMap.inside?
65 if target.y < 0 or target.x < 0 or \
66 target.y >= self.size.y or target.x >= self.size.x:
70 def move_yxyx(self, start_yxyx, direction):
71 mover = getattr(self, 'move__' + direction)
72 start_yx = self.undouble_yxyx(*start_yxyx)
73 target_yx = mover(start_yx)
74 return self.double_yx(target_yx)
76 def double_yx(self, absolute_yx):
77 big_y = absolute_yx.y // self.size.y
78 little_y = absolute_yx.y % self.size.y
79 big_x = absolute_yx.x // self.size.x
80 little_x = absolute_yx.x % self.size.x
81 return YX(big_y, big_x), YX(little_y, little_x)
83 def undouble_yxyx(self, big_yx, little_yx):
84 y = big_yx.y * self.size.y + little_yx.y
85 x = big_yx.x * self.size.x + little_yx.x
90 class MapGeometryWithLeftRightMoves(MapGeometry):
92 def move__LEFT(self, start_pos):
93 return YX(start_pos.y, start_pos.x - 1)
95 def move__RIGHT(self, start_pos):
96 return YX(start_pos.y, start_pos.x + 1)
100 class MapGeometrySquare(MapGeometryWithLeftRightMoves):
102 def __init__(self, *args, **kwargs):
103 super().__init__(*args, **kwargs)
104 self.fov_map_class = FovMapSquare
106 def define_segment(self, source_center, radius):
107 source_center = self.undouble_yxyx(*source_center)
108 size = YX(2 * radius + 1, 2 * radius + 1)
109 offset = YX(source_center.y - radius, source_center.x - radius)
110 center = YX(radius, radius)
111 return size, offset, center
113 def move__UP(self, start_pos):
114 return YX(start_pos.y - 1, start_pos.x)
116 def move__DOWN(self, start_pos):
117 return YX(start_pos.y + 1, start_pos.x)
120 class MapGeometryHex(MapGeometryWithLeftRightMoves):
122 def __init__(self, *args, **kwargs):
123 super().__init__(*args, **kwargs)
124 self.fov_map_class = FovMapHex
126 def define_segment(self, source_center, radius):
127 source_center = self.undouble_yxyx(*source_center)
128 indent = 1 if (source_center.y % 2) else 0
129 size = YX(2 * radius + 1 + indent, 2 * radius + 1)
130 offset = YX(source_center.y - radius - indent, source_center.x - radius)
131 center = YX(radius + indent, radius)
132 return size, offset, center
134 def move__UPLEFT(self, start_pos):
135 start_indented = start_pos.y % 2
137 return YX(start_pos.y - 1, start_pos.x)
139 return YX(start_pos.y - 1, start_pos.x - 1)
141 def move__UPRIGHT(self, start_pos):
142 start_indented = start_pos.y % 2
144 return YX(start_pos.y - 1, start_pos.x + 1)
146 return YX(start_pos.y - 1, start_pos.x)
148 def move__DOWNLEFT(self, start_pos):
149 start_indented = start_pos.y % 2
151 return YX(start_pos.y + 1, start_pos.x)
153 return YX(start_pos.y + 1, start_pos.x - 1)
155 def move__DOWNRIGHT(self, start_pos):
156 start_indented = start_pos.y % 2
158 return YX(start_pos.y + 1, start_pos.x + 1)
160 return YX(start_pos.y + 1, start_pos.x)
166 def __init__(self, map_geometry):
167 self.geometry = map_geometry
168 self.terrain = '.' * self.size_i
170 def __getitem__(self, yx):
171 return self.terrain[self.get_position_index(yx)]
173 def __setitem__(self, yx, c):
174 pos_i = self.get_position_index(yx)
176 self.terrain = self.terrain[:pos_i] + c + self.terrain[pos_i + 1:]
178 self.terrain[pos_i] = c
181 """Iterate over YX position coordinates."""
182 for y in range(self.geometry.size.y):
183 for x in range(self.geometry.size.x):
188 return self.geometry.size.y * self.geometry.size.x
190 def set_line(self, y, line):
191 height_map = self.geometry.size.y
192 width_map = self.geometry.size.x
194 raise ArgError('too large row number %s' % y)
195 width_line = len(line)
196 if width_line != width_map:
197 raise ArgError('map line width %s unequal map width %s' % (width_line, width_map))
198 self.terrain = self.terrain[:y * width_map] + line +\
199 self.terrain[(y + 1) * width_map:]
201 def get_position_index(self, yx):
202 return yx.y * self.geometry.size.x + yx.x
205 width = self.geometry.size.x
206 for y in range(self.geometry.size.y):
207 yield (y, self.terrain[y * width:(y + 1) * width])
211 class SourcedMap(Map):
213 def __init__(self, things, source_maps, source_center, radius, get_map):
215 example_map = get_map(YX(0, 0))
216 self.source_geometry = example_map.geometry
217 size, self.offset, self.center = \
218 self.source_geometry.define_segment(source_center, radius)
219 self.geometry = self.source_geometry.__class__(size)
221 big_yx, _ = self.source_yxyx(yx)
223 self.source_map_segment = ''
225 for yxyx in [t.position for t in things if t.blocking]:
226 if yxyx == source_center:
228 if yxyx[0] not in obstacles:
229 obstacles[yxyx[0]] = []
230 obstacles[yxyx[0]] += [yxyx[1]]
232 big_yx, little_yx = self.source_yxyx(yx)
233 if big_yx in obstacles and little_yx in obstacles[big_yx]:
234 self.source_map_segment += 'X'
236 self.source_map_segment += source_maps[big_yx][little_yx]
238 def source_yxyx(self, yx):
239 absolute_yx = yx + self.offset
240 big_yx, little_yx = self.source_geometry.double_yx(absolute_yx)
241 return big_yx, little_yx
243 def target_yx(self, big_yx, little_yx, check=False):
244 target_yx = self.source_geometry.undouble_yxyx(big_yx, little_yx) - self.offset
245 if check and not self.inside(target_yx):
249 def inside(self, yx):
250 if yx.y < 0 or yx.x < 0 or \
251 yx.y >= self.geometry.size.y or yx.x >= self.geometry.size.x:
257 class DijkstraMap(SourcedMap):
259 def __init__(self, *args, **kwargs):
260 super().__init__(*args, **kwargs)
261 self.terrain = [255] * self.size_i
262 self[self.center] = 0
266 for i in range(self.size_i):
267 if self.source_map_segment[i] in 'X=':
269 neighbors = self.geometry.get_neighbors_i(i)
270 for direction in [d for d in neighbors if neighbors[d]]:
271 j = neighbors[direction]
272 if self.terrain[j] < self.terrain[i] - 1:
273 self.terrain[i] = self.terrain[j] + 1
275 # print('DEBUG Dijkstra')
278 # for n in self.terrain:
279 # line_to_print += ['%3s' % n]
281 # if x >= self.geometry.size.x:
283 # print(' '.join(line_to_print))
288 class FovMap(SourcedMap):
289 # TODO: player visibility asymmetrical (A can see B when B can't see A):
290 # does this make sense, or not?
292 def __init__(self, *args, **kwargs):
293 super().__init__(*args, **kwargs)
294 self.terrain = '?' * self.size_i
295 self[self.center] = '.'
296 self.shadow_cones = []
297 #self.circle_out(self.center, self.shadow_process)
299 def init_terrain(self):
300 # we outsource this to allow multiprocessing some stab at it,
301 # and return it since multiprocessing does not modify its
303 self.circle_out(self.center, self.shadow_process)
306 def throws_shadow(self, yx):
307 return self.source_map_segment[self.get_position_index(yx)] == 'X'
309 def shadow_process(self, yx, distance_to_center, dir_i, dir_progress):
310 # Possible optimization: If no shadow_cones yet and self[yx] == '.',
312 CIRCLE = 360 # Since we'll float anyways, number is actually arbitrary.
314 def correct_arm(arm):
319 def in_shadow_cone(new_cone):
320 for old_cone in self.shadow_cones:
321 if old_cone[0] <= new_cone[0] and \
322 new_cone[1] <= old_cone[1]:
324 # We might want to also shade tiles whose middle arm is inside a
325 # shadow cone for a darker FOV. Note that we then could not for
326 # optimization purposes rely anymore on the assumption that a
327 # shaded tile cannot add growth to existing shadow cones.
330 def merge_cone(new_cone):
332 for old_cone in self.shadow_cones:
333 if new_cone[0] < old_cone[0] and \
334 (new_cone[1] > old_cone[0] or
335 math.isclose(new_cone[1], old_cone[0])):
336 old_cone[0] = new_cone[0]
338 if new_cone[1] > old_cone[1] and \
339 (new_cone[0] < old_cone[1] or
340 math.isclose(new_cone[0], old_cone[1])):
341 old_cone[1] = new_cone[1]
346 if in_shadow_cone(cone):
349 if self.throws_shadow(yx):
351 while merge_cone(cone):
354 self.shadow_cones += [cone]
356 step_size = (CIRCLE / len(self.circle_out_directions)) / distance_to_center
357 number_steps = dir_i * distance_to_center + dir_progress
358 left_arm = correct_arm(step_size / 2 + step_size * number_steps)
359 right_arm = correct_arm(left_arm + step_size)
361 # Optimization potential: left cone could be derived from previous
362 # right cone. Better even: Precalculate all cones.
363 if right_arm < left_arm:
364 eval_cone([left_arm, CIRCLE])
365 eval_cone([0, right_arm])
367 eval_cone([left_arm, right_arm])
369 def basic_circle_out_move(self, pos, direction):
370 mover = getattr(self.geometry, 'move__' + direction)
373 def circle_out(self, yx, f):
374 # Optimization potential: Precalculate movement positions. (How to check
375 # circle_in_map then?)
376 # Optimization potential: Precalculate what tiles are shaded by what tile
377 # and skip evaluation of already shaded tile. (This only works if tiles
378 # shading implies they completely lie in existing shades; otherwise we
379 # would lose shade growth through tiles at shade borders.)
382 while distance <= self.radius:
383 yx = self.basic_circle_out_move(yx, 'RIGHT')
384 for dir_i in range(len(self.circle_out_directions)):
385 for dir_progress in range(distance):
386 direction = self.circle_out_directions[dir_i]
387 yx = self.circle_out_move(yx, direction)
388 f(yx, distance, dir_i, dir_progress)
394 class FovMapHex(FovMap):
395 circle_out_directions = ('DOWNLEFT', 'LEFT', 'UPLEFT',
396 'UPRIGHT', 'RIGHT', 'DOWNRIGHT')
398 def circle_out_move(self, yx, direction):
399 return self.basic_circle_out_move(yx, direction)
403 class FovMapSquare(FovMap):
404 circle_out_directions = (('DOWN', 'LEFT'), ('LEFT', 'UP'),
405 ('UP', 'RIGHT'), ('RIGHT', 'DOWN'))
407 def circle_out_move(self, yx, direction):
408 yx = self.basic_circle_out_move(yx, direction[0])
409 return self.basic_circle_out_move(yx, direction[1])