home · contact · privacy
Fix bug that blocked sound from reaching players.
[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
25     def get_directions(self):
26         directions = []
27         prefix = 'move__'
28         for name in dir(self):
29             if name[:len(prefix)] == prefix:
30                 directions += [name[len(prefix):]]
31         return directions
32
33     def get_neighbors_yxyx(self, yxyx):
34         neighbors = {}
35         for direction in self.get_directions():
36             neighbors[direction] = self.move_yxyx(yxyx, direction)
37         return neighbors
38
39     def get_neighbors_yx(self, pos):
40         neighbors = {}
41         for direction in self.get_directions():
42             neighbors[direction] = self.move_yx(pos, direction)
43         return neighbors
44
45     def get_neighbors_i(self, i):
46         if i in self.neighbors_i:
47             return self.neighbors_i[i]
48         pos = YX(i // self.size.x, i % self.size.x)
49         neighbors_pos = self.get_neighbors_yx(pos)
50         neighbors_i = {}
51         for direction in neighbors_pos:
52             pos = neighbors_pos[direction]
53             if pos is None:
54                 neighbors_i[direction] = None
55             else:
56                 neighbors_i[direction] = pos.y * self.size.x + pos.x
57         self.neighbors_i[i] = neighbors_i
58         return self.neighbors_i[i]
59
60     def move_yx(self, start_yx, direction, check=True):
61         mover = getattr(self, 'move__' + direction)
62         target = mover(start_yx)
63         # TODO refactor with SourcedMap.inside?
64         if target.y < 0 or target.x < 0 or \
65            target.y >= self.size.y or target.x >= self.size.x:
66             return None
67         return target
68
69     def move_yxyx(self, start_yxyx, direction):
70         mover = getattr(self, 'move__' + direction)
71         start_yx = self.undouble_yxyx(*start_yxyx)
72         target_yx = mover(start_yx)
73         return self.double_yx(target_yx)
74
75     def double_yx(self, absolute_yx):
76         big_y = absolute_yx.y // self.size.y
77         little_y = absolute_yx.y % self.size.y
78         big_x = absolute_yx.x // self.size.x
79         little_x = absolute_yx.x % self.size.x
80         return YX(big_y, big_x), YX(little_y, little_x)
81
82     def undouble_yxyx(self, big_yx, little_yx):
83         y = big_yx.y * self.size.y + little_yx.y
84         x = big_yx.x * self.size.x + little_yx.x
85         return YX(y, x)
86
87
88
89 class MapGeometryWithLeftRightMoves(MapGeometry):
90
91     def move__LEFT(self, start_pos):
92         return YX(start_pos.y, start_pos.x - 1)
93
94     def move__RIGHT(self, start_pos):
95         return YX(start_pos.y, start_pos.x + 1)
96
97
98
99 class MapGeometrySquare(MapGeometryWithLeftRightMoves):
100
101     def __init__(self, *args, **kwargs):
102         super().__init__(*args, **kwargs)
103         self.fov_map_class = FovMapSquare
104
105     def define_segment(self, source_center, radius):
106         source_center = self.undouble_yxyx(*source_center)
107         size = YX(2 * radius + 1, 2 * radius + 1)
108         offset = YX(source_center.y - radius, source_center.x - radius)
109         center = YX(radius, radius)
110         return size, offset, center
111
112     def move__UP(self, start_pos):
113         return YX(start_pos.y - 1, start_pos.x)
114
115     def move__DOWN(self, start_pos):
116         return YX(start_pos.y + 1, start_pos.x)
117
118
119 class MapGeometryHex(MapGeometryWithLeftRightMoves):
120
121     def __init__(self, *args, **kwargs):
122         super().__init__(*args, **kwargs)
123         self.fov_map_class = FovMapHex
124
125     def define_segment(self, source_center, radius):
126         source_center = self.undouble_yxyx(*source_center)
127         indent = 1 if (source_center.y % 2) else 0
128         size = YX(2 * radius + 1 + indent, 2 * radius + 1)
129         offset = YX(source_center.y - radius - indent, source_center.x - radius)
130         center = YX(radius + indent, radius)
131         return size, offset, center
132
133     def move__UPLEFT(self, start_pos):
134         start_indented = start_pos.y % 2
135         if start_indented:
136             return YX(start_pos.y - 1, start_pos.x)
137         else:
138             return YX(start_pos.y - 1, start_pos.x - 1)
139
140     def move__UPRIGHT(self, start_pos):
141         start_indented = start_pos.y % 2
142         if start_indented:
143             return YX(start_pos.y - 1, start_pos.x + 1)
144         else:
145             return YX(start_pos.y - 1, start_pos.x)
146
147     def move__DOWNLEFT(self, start_pos):
148         start_indented = start_pos.y % 2
149         if start_indented:
150             return YX(start_pos.y + 1, start_pos.x)
151         else:
152             return YX(start_pos.y + 1, start_pos.x - 1)
153
154     def move__DOWNRIGHT(self, start_pos):
155         start_indented = start_pos.y % 2
156         if start_indented:
157             return YX(start_pos.y + 1, start_pos.x + 1)
158         else:
159             return YX(start_pos.y + 1, start_pos.x)
160
161
162
163 class Map():
164
165     def __init__(self, map_geometry):
166         self.geometry = map_geometry
167         self.terrain = '.' * self.size_i
168
169     def __getitem__(self, yx):
170         return self.terrain[self.get_position_index(yx)]
171
172     def __setitem__(self, yx, c):
173         pos_i = self.get_position_index(yx)
174         if type(c) == str:
175             self.terrain = self.terrain[:pos_i] + c + self.terrain[pos_i + 1:]
176         else:
177             self.terrain[pos_i] = c
178
179     def __iter__(self):
180         """Iterate over YX position coordinates."""
181         for y in range(self.geometry.size.y):
182             for x in range(self.geometry.size.x):
183                 yield YX(y, x)
184
185     @property
186     def size_i(self):
187         return self.geometry.size.y * self.geometry.size.x
188
189     def set_line(self, y, line):
190         height_map = self.geometry.size.y
191         width_map = self.geometry.size.x
192         if y >= height_map:
193             raise ArgError('too large row number %s' % y)
194         width_line = len(line)
195         if width_line != width_map:
196             raise ArgError('map line width %s unequal map width %s' % (width_line, width_map))
197         self.terrain = self.terrain[:y * width_map] + line +\
198             self.terrain[(y + 1) * width_map:]
199
200     def get_position_index(self, yx):
201         return yx.y * self.geometry.size.x + yx.x
202
203     def lines(self):
204         width = self.geometry.size.x
205         for y in range(self.geometry.size.y):
206             yield (y, self.terrain[y * width:(y + 1) * width])
207
208
209
210 class SourcedMap(Map):
211
212     def __init__(self, things, source_maps, source_center, radius, get_map):
213         self.source_maps = source_maps
214         self.radius = radius
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)
220         for yx in self:
221             big_yx, _ = self.source_yxyx(yx)
222             get_map(big_yx)
223         self.source_map_segment = ''
224         obstacles = {}
225         for yxyx in [t.position for t in things if t.blocking]:
226             if yxyx == source_center:
227                 continue
228             if yxyx[0] not in obstacles:
229                 obstacles[yxyx[0]] = []
230             obstacles[yxyx[0]] += [yxyx[1]]
231         for yx in self:
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'
235             else:
236                 self.source_map_segment += self.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, *args, **kwargs):
260         super().__init__(*args, **kwargs)
261         self.terrain = [255] * self.size_i
262         self[self.center] = 0
263         shrunk = True
264         while shrunk:
265             shrunk = False
266             for i in range(self.size_i):
267                 if self.source_map_segment[i] == 'X':
268                     continue
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
274                         shrunk = True
275         # print('DEBUG Dijkstra')
276         # line_to_print = []
277         # x = 0
278         # for n in self.terrain:
279         #     line_to_print += ['%3s' % n]
280         #     x += 1
281         #     if x >= self.geometry.size.x:
282         #         x = 0
283         #         print(' '.join(line_to_print))
284         #         line_to_print = []
285
286
287
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?
291
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)
298
299     def throws_shadow(self, yx):
300         return self.source_map_segment[self.get_position_index(yx)] == 'X'
301
302     def shadow_process(self, yx, distance_to_center, dir_i, dir_progress):
303         # Possible optimization: If no shadow_cones yet and self[yx] == '.',
304         # skip all.
305         CIRCLE = 360  # Since we'll float anyways, number is actually arbitrary.
306
307         def correct_arm(arm):
308             if arm > CIRCLE:
309                 arm -= CIRCLE
310             return arm
311
312         def in_shadow_cone(new_cone):
313             for old_cone in self.shadow_cones:
314                 if old_cone[0] <= new_cone[0] and \
315                    new_cone[1] <= old_cone[1]:
316                     return True
317                 # We might want to also shade tiles whose middle arm is inside a
318                 # shadow cone for a darker FOV. Note that we then could not for
319                 # optimization purposes rely anymore on the assumption that a
320                 # shaded tile cannot add growth to existing shadow cones.
321             return False
322
323         def merge_cone(new_cone):
324             import math
325             for old_cone in self.shadow_cones:
326                 if new_cone[0] < old_cone[0] and \
327                     (new_cone[1] > old_cone[0] or
328                      math.isclose(new_cone[1], old_cone[0])):
329                     old_cone[0] = new_cone[0]
330                     return True
331                 if new_cone[1] > old_cone[1] and \
332                     (new_cone[0] < old_cone[1] or
333                      math.isclose(new_cone[0], old_cone[1])):
334                     old_cone[1] = new_cone[1]
335                     return True
336             return False
337
338         def eval_cone(cone):
339             if in_shadow_cone(cone):
340                 return
341             self[yx] = '.'
342             if self.throws_shadow(yx):
343                 unmerged = True
344                 while merge_cone(cone):
345                     unmerged = False
346                 if unmerged:
347                     self.shadow_cones += [cone]
348
349         step_size = (CIRCLE / len(self.circle_out_directions)) / distance_to_center
350         number_steps = dir_i * distance_to_center + dir_progress
351         left_arm = correct_arm(step_size / 2 + step_size * number_steps)
352         right_arm = correct_arm(left_arm + step_size)
353
354         # Optimization potential: left cone could be derived from previous
355         # right cone. Better even: Precalculate all cones.
356         if right_arm < left_arm:
357             eval_cone([left_arm, CIRCLE])
358             eval_cone([0, right_arm])
359         else:
360             eval_cone([left_arm, right_arm])
361
362     def basic_circle_out_move(self, pos, direction):
363         mover = getattr(self.geometry, 'move__' + direction)
364         return mover(pos)
365
366     def circle_out(self, yx, f):
367         # Optimization potential: Precalculate movement positions. (How to check
368         # circle_in_map then?)
369         # Optimization potential: Precalculate what tiles are shaded by what tile
370         # and skip evaluation of already shaded tile. (This only works if tiles
371         # shading implies they completely lie in existing shades; otherwise we
372         # would lose shade growth through tiles at shade borders.)
373         distance = 1
374         yx = YX(yx.y, yx.x)
375         while distance <= self.radius:
376             yx = self.basic_circle_out_move(yx, 'RIGHT')
377             for dir_i in range(len(self.circle_out_directions)):
378                 for dir_progress in range(distance):
379                     direction = self.circle_out_directions[dir_i]
380                     yx = self.circle_out_move(yx, direction)
381                     f(yx, distance, dir_i, dir_progress)
382             distance += 1
383
384
385
386
387 class FovMapHex(FovMap):
388     circle_out_directions = ('DOWNLEFT', 'LEFT', 'UPLEFT',
389                              'UPRIGHT', 'RIGHT', 'DOWNRIGHT')
390
391     def circle_out_move(self, yx, direction):
392         return self.basic_circle_out_move(yx, direction)
393
394
395
396 class FovMapSquare(FovMap):
397     circle_out_directions = (('DOWN', 'LEFT'), ('LEFT', 'UP'),
398                              ('UP', 'RIGHT'), ('RIGHT', 'DOWN'))
399
400     def circle_out_move(self, yx, direction):
401         yx = self.basic_circle_out_move(yx, direction[0])
402         return self.basic_circle_out_move(yx, direction[1])