home · contact · privacy
Add crates.
[plomrogue2] / plomrogue / mapping.py
1 import collections
2 from plomrogue.errors import ArgError
3
4
5
6 class YX(collections.namedtuple('YX', ('y', 'x'))):
7
8     def __add__(self, other):
9         return YX(self.y + other.y, self.x + other.x)
10
11     def __sub__(self, other):
12         return YX(self.y - other.y, self.x - other.x)
13
14     def __str__(self):
15         return 'Y:%s,X:%s' % (self.y, self.x)
16
17
18
19 class MapGeometry():
20
21     def __init__(self, size):
22         self.size = size
23         self.neighbors_i = {}
24         self.directions = self.get_directions()
25
26     def get_directions(self):
27         directions = []
28         prefix = 'move__'
29         for name in dir(self):
30             if name[:len(prefix)] == prefix:
31                 directions += [name[len(prefix):]]
32         return directions
33
34     def get_neighbors_yxyx(self, yxyx):
35         neighbors = {}
36         for direction in self.directions:
37             neighbors[direction] = self.move_yxyx(yxyx, direction)
38         return neighbors
39
40     def get_neighbors_yx(self, pos):
41         neighbors = {}
42         for direction in self.directions:
43             neighbors[direction] = self.move_yx(pos, direction)
44         return neighbors
45
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)
51         neighbors_i = {}
52         for direction in neighbors_pos:
53             pos = neighbors_pos[direction]
54             if pos is None:
55                 neighbors_i[direction] = None
56             else:
57                 neighbors_i[direction] = pos.y * self.size.x + pos.x
58         self.neighbors_i[i] = neighbors_i
59         return self.neighbors_i[i]
60
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:
67             return None
68         return target
69
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)
75
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)
82
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
86         return YX(y, x)
87
88     def basic_circle_out_move(self, position, direction):
89         mover = getattr(self, 'move__' + direction)
90         return mover(position)
91
92
93
94 class MapGeometryWithLeftRightMoves(MapGeometry):
95
96     def move__LEFT(self, start_pos):
97         return YX(start_pos.y, start_pos.x - 1)
98
99     def move__RIGHT(self, start_pos):
100         return YX(start_pos.y, start_pos.x + 1)
101
102
103
104 class MapGeometrySquare(MapGeometryWithLeftRightMoves):
105     circle_out_directions = (('DOWN', 'LEFT'), ('LEFT', 'UP'),
106                              ('UP', 'RIGHT'), ('RIGHT', 'DOWN'))
107
108     def circle_out_move(self, yx, direction):
109         yx = self.basic_circle_out_move(yx, direction[0])
110         return self.basic_circle_out_move(yx, direction[1])
111
112     def define_segment(self, source_center, radius):
113         source_center = self.undouble_yxyx(*source_center)
114         size = YX(2 * radius + 1, 2 * radius + 1)
115         offset = YX(source_center.y - radius, source_center.x - radius)
116         center = YX(radius, radius)
117         return size, offset, center
118
119     def move__UP(self, start_pos):
120         return YX(start_pos.y - 1, start_pos.x)
121
122     def move__DOWN(self, start_pos):
123         return YX(start_pos.y + 1, start_pos.x)
124
125
126 class MapGeometryHex(MapGeometryWithLeftRightMoves):
127     circle_out_directions = ('DOWNLEFT', 'LEFT', 'UPLEFT',
128                              'UPRIGHT', 'RIGHT', 'DOWNRIGHT')
129
130     def circle_out_move(self, yx, direction):
131         return self.basic_circle_out_move(yx, direction)
132
133     def define_segment(self, source_center, radius):
134         source_center = self.undouble_yxyx(*source_center)
135         indent = 1 if (source_center.y % 2) else 0
136         size = YX(2 * radius + 1 + indent, 2 * radius + 1)
137         offset = YX(source_center.y - radius - indent, source_center.x - radius)
138         center = YX(radius + indent, radius)
139         return size, offset, center
140
141     def move__UPLEFT(self, start_pos):
142         start_indented = start_pos.y % 2
143         if start_indented:
144             return YX(start_pos.y - 1, start_pos.x)
145         else:
146             return YX(start_pos.y - 1, start_pos.x - 1)
147
148     def move__UPRIGHT(self, start_pos):
149         start_indented = start_pos.y % 2
150         if start_indented:
151             return YX(start_pos.y - 1, start_pos.x + 1)
152         else:
153             return YX(start_pos.y - 1, start_pos.x)
154
155     def move__DOWNLEFT(self, start_pos):
156         start_indented = start_pos.y % 2
157         if start_indented:
158             return YX(start_pos.y + 1, start_pos.x)
159         else:
160             return YX(start_pos.y + 1, start_pos.x - 1)
161
162     def move__DOWNRIGHT(self, start_pos):
163         start_indented = start_pos.y % 2
164         if start_indented:
165             return YX(start_pos.y + 1, start_pos.x + 1)
166         else:
167             return YX(start_pos.y + 1, start_pos.x)
168
169
170
171 class Map():
172
173     def __init__(self, map_geometry):
174         self.geometry = map_geometry
175         self.terrain = '.' * self.size_i  # TODO: use Game.get_flatland()?
176
177     def __getitem__(self, yx):
178         return self.terrain[self.get_position_index(yx)]
179
180     def __setitem__(self, yx, c):
181         pos_i = self.get_position_index(yx)
182         if type(c) == str:
183             self.terrain = self.terrain[:pos_i] + c + self.terrain[pos_i + 1:]
184         else:
185             self.terrain[pos_i] = c
186
187     def __iter__(self):
188         """Iterate over YX position coordinates."""
189         for y in range(self.geometry.size.y):
190             for x in range(self.geometry.size.x):
191                 yield YX(y, x)
192
193     @property
194     def size_i(self):
195         return self.geometry.size.y * self.geometry.size.x
196
197     def set_line(self, y, line):
198         height_map = self.geometry.size.y
199         width_map = self.geometry.size.x
200         if y >= height_map:
201             raise ArgError('too large row number %s' % y)
202         width_line = len(line)
203         if width_line != width_map:
204             raise ArgError('map line width %s unequal map width %s' % (width_line, width_map))
205         self.terrain = self.terrain[:y * width_map] + line +\
206             self.terrain[(y + 1) * width_map:]
207
208     def get_position_index(self, yx):
209         return yx.y * self.geometry.size.x + yx.x
210
211     def lines(self):
212         width = self.geometry.size.x
213         for y in range(self.geometry.size.y):
214             yield (y, self.terrain[y * width:(y + 1) * width])
215
216
217
218 class SourcedMap(Map):
219
220     def __init__(self, block_chars, obstacle_positions, source_maps,
221                  source_center, radius, get_map):
222         self.block_chars = block_chars
223         self.radius = radius
224         example_map = get_map(YX(0, 0))
225         self.source_geometry = example_map.geometry
226         size, self.offset, self.center = \
227             self.source_geometry.define_segment(source_center, radius)
228         self.geometry = self.source_geometry.__class__(size)
229         self.source_map_segment = ''
230         for yx in self:
231             big_yx, little_yx = self.source_yxyx(yx)
232             get_map(big_yx)
233             if (big_yx, little_yx) in obstacle_positions:
234                 self.source_map_segment += self.block_chars[0]
235             else:
236                 self.source_map_segment += source_maps[big_yx][little_yx]
237
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
242
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):
246             return False
247         return target_yx
248
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:
252             return False
253         return True
254
255
256
257 class DijkstraMap(SourcedMap):
258
259     def __init__(self, potential_targets, *args, **kwargs):
260         # TODO: check potential optimizations:
261         # - somehow ignore tiles that have the lowest possible value (we can
262         #   compare with a precalculated map for given starting position)
263         # - check if Python offers more efficient data structures to use here
264         super().__init__(*args, **kwargs)
265         self.terrain = [255] * self.size_i
266         self[self.center] = 0
267         targets = []
268         for target_yxyx in potential_targets:
269             target = self.target_yx(*target_yxyx)
270             if target == self.center:
271                 continue
272             if self.inside(target):
273                 targets += [target]
274
275         def work_tile(position_i):
276             shrunk_test = False
277             if self.source_map_segment[position_i] in self.block_chars:
278                 return shrunk_test
279             neighbors = self.geometry.get_neighbors_i(position_i)
280             for direction in [d for d in neighbors if neighbors[d]]:
281                 j = neighbors[direction]
282                 if self.terrain[j] < self.terrain[position_i] - 1:
283                     self.terrain[position_i] = self.terrain[j] + 1
284                     shrunk_test = True
285             return shrunk_test
286
287         # TODO: refactor with FovMap.circle_out()
288         shrunk = True
289         while shrunk and len(targets) > 0:
290             shrunk = False
291             yx = self.center
292             distance = 1
293             while distance <= self.radius and len(targets) > 0:
294                 yx = self.geometry.basic_circle_out_move(yx, 'RIGHT')
295                 for dir_i in range(len(self.geometry.circle_out_directions)):
296                     for dir_progress in range(distance):
297                         direction = self.geometry.circle_out_directions[dir_i]
298                         yx = self.geometry.circle_out_move(yx, direction)
299                         position_i = self.get_position_index(yx)
300                         cur_shrunk = work_tile(position_i)
301                         if cur_shrunk and yx in targets:
302                             targets.remove(yx)
303                         shrunk = shrunk or cur_shrunk
304                 distance += 1
305         # print('DEBUG Dijkstra')
306         # line_to_print = []
307         # x = 0
308         # for n in self.terrain:
309         #     line_to_print += ['%3s' % n]
310         #     x += 1
311         #     if x >= self.geometry.size.x:
312         #         x = 0
313         #         print(' '.join(line_to_print))
314         #         line_to_print = []
315
316
317
318 class FovMap(SourcedMap):
319     # TODO: player visibility asymmetrical (A can see B when B can't see A):
320     # does this make sense, or not?
321
322     def __init__(self, *args, **kwargs):
323         super().__init__(*args, **kwargs)
324         self.terrain = '?' * self.size_i
325         self[self.center] = '.'
326         self.shadow_cones = []
327         #self.circle_out(self.center, self.shadow_process)
328
329     def init_terrain(self):
330         # we outsource this to allow multiprocessing some stab at it,
331         # and return it since multiprocessing does not modify its
332         # processing sources
333         self.circle_out(self.center, self.shadow_process)
334         return self
335
336     def throws_shadow(self, yx):
337         return self.source_map_segment[self.get_position_index(yx)]\
338             in self.block_chars
339
340     def shadow_process(self, yx, distance_to_center, dir_i, dir_progress):
341         # Possible optimization: If no shadow_cones yet and self[yx] == '.',
342         # skip all.
343         CIRCLE = 360  # Since we'll float anyways, number is actually arbitrary.
344
345         def correct_arm(arm):
346             if arm > CIRCLE:
347                 arm -= CIRCLE
348             return arm
349
350         def in_shadow_cone(new_cone):
351             for old_cone in self.shadow_cones:
352                 if old_cone[0] <= new_cone[0] and \
353                    new_cone[1] <= old_cone[1]:
354                     return True
355                 # We might want to also shade tiles whose middle arm is inside a
356                 # shadow cone for a darker FOV. Note that we then could not for
357                 # optimization purposes rely anymore on the assumption that a
358                 # shaded tile cannot add growth to existing shadow cones.
359             return False
360
361         def merge_cone(new_cone):
362             import math
363             for old_cone in self.shadow_cones:
364                 if new_cone[0] < old_cone[0] and \
365                     (new_cone[1] > old_cone[0] or
366                      math.isclose(new_cone[1], old_cone[0])):
367                     old_cone[0] = new_cone[0]
368                     return True
369                 if new_cone[1] > old_cone[1] and \
370                     (new_cone[0] < old_cone[1] or
371                      math.isclose(new_cone[0], old_cone[1])):
372                     old_cone[1] = new_cone[1]
373                     return True
374             return False
375
376         def eval_cone(cone):
377             if in_shadow_cone(cone):
378                 return
379             self[yx] = '.'
380             if self.throws_shadow(yx):
381                 unmerged = True
382                 while merge_cone(cone):
383                     unmerged = False
384                 if unmerged:
385                     self.shadow_cones += [cone]
386
387         step_size = (CIRCLE / len(self.geometry.circle_out_directions))\
388             / distance_to_center
389         number_steps = dir_i * distance_to_center + dir_progress
390         left_arm = correct_arm(step_size / 2 + step_size * number_steps)
391         right_arm = correct_arm(left_arm + step_size)
392
393         # Optimization potential: left cone could be derived from previous
394         # right cone. Better even: Precalculate all cones.
395         if right_arm < left_arm:
396             eval_cone([left_arm, CIRCLE])
397             eval_cone([0, right_arm])
398         else:
399             eval_cone([left_arm, right_arm])
400
401     def circle_out(self, yx, f):
402         # Optimization potential: Precalculate movement positions.
403         # Optimization potential: Precalculate what tiles are shaded by what tile
404         # and skip evaluation of already shaded tile. (This only works if tiles
405         # shading implies they completely lie in existing shades; otherwise we
406         # would lose shade growth through tiles at shade borders.)
407         distance = 1
408         yx = YX(yx.y, yx.x)
409         while distance <= self.radius:
410             yx = self.geometry.basic_circle_out_move(yx, 'RIGHT')
411             for dir_i in range(len(self.geometry.circle_out_directions)):
412                 for dir_progress in range(distance):
413                     direction = self.geometry.circle_out_directions[dir_i]
414                     yx = self.geometry.circle_out_move(yx, direction)
415                     f(yx, distance, dir_i, dir_progress)
416             distance += 1