home · contact · privacy
Use self.max_map_awakeness to recude magic numbering.
[plomrogue2-experiments] / new / plomrogue / mapping.py
1 from plomrogue.errors import ArgError
2 import collections
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 Map:
20
21     def __init__(self, size=YX(0, 0), init_char = '?', start_indented=True,
22                  awakeness=0):
23         self.size = size
24         self.terrain = init_char * self.size_i
25         self.start_indented = start_indented
26         self.awake = awakeness  # asleep if zero
27         self.stats = {}
28
29     def __getitem__(self, yx):
30         return self.terrain[self.get_position_index(yx)]
31
32     def __setitem__(self, yx, c):
33         pos_i = self.get_position_index(yx)
34         if type(c) == str:
35             self.terrain = self.terrain[:pos_i] + c + self.terrain[pos_i + 1:]
36         else:
37             self.terrain[pos_i] = c
38
39     def __iter__(self):
40         """Iterate over YX position coordinates."""
41         for y in range(self.size.y):
42             for x in range(self.size.x):
43                 yield YX(y, x)
44
45     @property
46     def size_i(self):
47         return self.size.y * self.size.x
48
49     def set_line(self, y, line):
50         height_map = self.size.y
51         width_map = self.size.x
52         if y >= height_map:
53             raise ArgError('too large row number %s' % y)
54         width_line = len(line)
55         if width_line > width_map:
56             raise ArgError('too large map line width %s' % width_line)
57         self.terrain = self.terrain[:y * width_map] + line +\
58                        self.terrain[(y + 1) * width_map:]
59
60     def get_position_index(self, yx):
61         return yx.y * self.size.x + yx.x
62
63     def lines(self):
64         width = self.size.x
65         for y in range(self.size.y):
66             yield (y, self.terrain[y * width:(y + 1) * width])
67
68
69
70 class MapGeometry():
71
72     def get_directions(self):
73         directions = []
74         for name in dir(self):
75             if name[:5] == 'move_':
76                 directions += [name[5:]]
77         return directions
78
79     def get_neighbors(self, pos, map_size, start_indented=True):
80         neighbors = {}
81         if not hasattr(self, 'neighbors_to'):
82             self.neighbors_to = {}
83         if not map_size in self.neighbors_to:
84             self.neighbors_to[map_size] = {}
85         if not start_indented in self.neighbors_to[map_size]:
86             self.neighbors_to[map_size][start_indented] = {}
87         if pos in self.neighbors_to[map_size][start_indented]:
88             return self.neighbors_to[map_size][start_indented][pos]
89         for direction in self.get_directions():
90             neighbors[direction] = self.move(pos, direction, map_size,
91                                              start_indented)
92         self.neighbors_to[map_size][start_indented][pos] = neighbors
93         return neighbors
94
95     def undouble_coordinate(self, maps_size, coordinate):
96         y = maps_size.y * coordinate[0].y + coordinate[1].y
97         x = maps_size.x * coordinate[0].x + coordinate[1].x
98         return YX(y, x)
99
100     def get_view_offset(self, maps_size, center, radius):
101         yx_to_origin = self.undouble_coordinate(maps_size, center)
102         return yx_to_origin - YX(radius, radius)
103
104     def pos_in_view(self, pos, offset, maps_size):
105         return self.undouble_coordinate(maps_size, pos) - offset
106
107     def get_view_and_seen_maps(self, maps_size, get_map, radius, view_offset):
108         m = Map(size=YX(radius*2+1, radius*2+1),
109                 start_indented=(view_offset.y % 2 == 0))
110         seen_maps = []
111         for pos in m:
112             seen_pos = self.correct_double_coordinate(maps_size, (0,0),
113                                                       pos + view_offset)
114             if seen_pos[0] not in seen_maps:
115                 seen_maps += [seen_pos[0]]
116             seen_map = get_map(seen_pos[0])
117             if seen_map is None:
118                 seen_map = Map(size=maps_size)
119             m[pos] = seen_map[seen_pos[1]]
120         return m, seen_maps
121
122     def correct_double_coordinate(self, map_size, big_yx, little_yx):
123
124         def adapt_axis(axis):
125             maps_crossed = little_yx[axis] // map_size[axis]
126             new_big = big_yx[axis] + maps_crossed
127             new_little = little_yx[axis] % map_size[axis]
128             return new_big, new_little
129
130         new_big_y, new_little_y = adapt_axis(0)
131         new_big_x, new_little_x = adapt_axis(1)
132         return YX(new_big_y, new_big_x), YX(new_little_y, new_little_x)
133
134     def move(self, start_pos, direction, map_size, start_indented=True):
135         mover = getattr(self, 'move_' + direction)
136         big_yx, little_yx = start_pos
137         uncorrected_target = mover(little_yx, start_indented)
138         return self.correct_double_coordinate(map_size, big_yx,
139                                               uncorrected_target)
140
141
142
143 class MapGeometryWithLeftRightMoves(MapGeometry):
144
145     def move_LEFT(self, start_pos, _):
146         return YX(start_pos.y, start_pos.x - 1)
147
148     def move_RIGHT(self, start_pos, _):
149         return YX(start_pos.y, start_pos.x + 1)
150
151
152
153 class MapGeometrySquare(MapGeometryWithLeftRightMoves):
154
155     def move_UP(self, start_pos, _):
156         return YX(start_pos.y - 1, start_pos.x)
157
158     def move_DOWN(self, start_pos, _):
159         return YX(start_pos.y + 1, start_pos.x)
160
161
162
163 class MapGeometryHex(MapGeometryWithLeftRightMoves):
164
165     def __init__(self, *args, **kwargs):
166         super().__init__(*args, **kwargs)
167         self.fov_map_type = FovMapHex
168
169     def move_UPLEFT(self, start_pos, start_indented):
170         if start_pos.y % 2 == start_indented:
171             return YX(start_pos.y - 1, start_pos.x - 1)
172         else:
173             return YX(start_pos.y - 1, start_pos.x)
174
175     def move_UPRIGHT(self, start_pos, start_indented):
176         if start_pos.y % 2 == start_indented:
177             return YX(start_pos.y - 1, start_pos.x)
178         else:
179             return YX(start_pos.y - 1, start_pos.x + 1)
180
181     def move_DOWNLEFT(self, start_pos, start_indented):
182         if start_pos.y % 2 == start_indented:
183              return YX(start_pos.y + 1, start_pos.x - 1)
184         else:
185                return YX(start_pos.y + 1, start_pos.x)
186
187     def move_DOWNRIGHT(self, start_pos, start_indented):
188         if start_pos.y % 2 == start_indented:
189             return YX(start_pos.y + 1, start_pos.x)
190         else:
191             return YX(start_pos.y + 1, start_pos.x + 1)
192
193
194
195 class FovMap(Map):
196
197     def __init__(self, source_map, center):
198         self.source_map = source_map
199         self.size = self.source_map.size
200         self.fov_radius = (self.size.y / 2) - 0.5
201         self.start_indented = source_map.start_indented
202         self.terrain = '?' * self.size_i
203         self[center] = '.'
204         self.shadow_cones = []
205         self.circle_out(center, self.shadow_process_hex)
206
207     def shadow_process_hex(self, yx, distance_to_center, dir_i, dir_progress):
208         # Possible optimization: If no shadow_cones yet and self[yx] == '.',
209         # skip all.
210         CIRCLE = 360  # Since we'll float anyways, number is actually arbitrary.
211
212         def correct_arm(arm):
213             if arm < 0:
214                 arm += CIRCLE
215             return arm
216
217         def in_shadow_cone(new_cone):
218             for old_cone in self.shadow_cones:
219                 if old_cone[0] >= new_cone[0] and \
220                     new_cone[1] >= old_cone[1]:
221                     #print('DEBUG shadowed by:', old_cone)
222                     return True
223                 # We might want to also shade hexes whose middle arm is inside a
224                 # shadow cone for a darker FOV. Note that we then could not for
225                 # optimization purposes rely anymore on the assumption that a
226                 # shaded hex cannot add growth to existing shadow cones.
227             return False
228
229         def merge_cone(new_cone):
230             import math
231             for old_cone in self.shadow_cones:
232                 if new_cone[0] > old_cone[0] and \
233                     (new_cone[1] < old_cone[0] or
234                      math.isclose(new_cone[1], old_cone[0])):
235                     #print('DEBUG merging to', old_cone)
236                     old_cone[0] = new_cone[0]
237                     #print('DEBUG merged cone:', old_cone)
238                     return True
239                 if new_cone[1] < old_cone[1] and \
240                     (new_cone[0] > old_cone[1] or
241                      math.isclose(new_cone[0], old_cone[1])):
242                     #print('DEBUG merging to', old_cone)
243                     old_cone[1] = new_cone[1]
244                     #print('DEBUG merged cone:', old_cone)
245                     return True
246             return False
247
248         def eval_cone(cone):
249             #print('DEBUG CONE', cone, '(', step_size, distance_to_center, number_steps, ')')
250             if in_shadow_cone(cone):
251                 return
252             self[yx] = '.'
253             if self.source_map[yx] != '.':
254                 #print('DEBUG throws shadow', cone)
255                 unmerged = True
256                 while merge_cone(cone):
257                     unmerged = False
258                 if unmerged:
259                     self.shadow_cones += [cone]
260
261         #print('DEBUG', yx)
262         step_size = (CIRCLE/len(self.circle_out_directions)) / distance_to_center
263         number_steps = dir_i * distance_to_center + dir_progress
264         left_arm = correct_arm(-(step_size/2) - step_size*number_steps)
265         right_arm = correct_arm(left_arm - step_size)
266         # Optimization potential: left cone could be derived from previous
267         # right cone. Better even: Precalculate all cones.
268         if right_arm > left_arm:
269             eval_cone([left_arm, 0])
270             eval_cone([CIRCLE, right_arm])
271         else:
272             eval_cone([left_arm, right_arm])
273
274     def basic_circle_out_move(self, pos, direction):
275         """Move position pos into direction. Return whether still in map."""
276         mover = getattr(self.geometry, 'move_' + direction)
277         pos = mover(pos, self.start_indented)
278         if pos.y < 0 or pos.x < 0 or \
279             pos.y >= self.size.y or pos.x >= self.size.x:
280             return pos, False
281         return pos, True
282
283     def circle_out(self, yx, f):
284         # Optimization potential: Precalculate movement positions. (How to check
285         # circle_in_map then?)
286         # Optimization potential: Precalculate what hexes are shaded by what hex
287         # and skip evaluation of already shaded hexes. (This only works if hex
288         # shading implies they completely lie in existing shades; otherwise we
289         # would lose shade growth through hexes at shade borders.)
290
291         # TODO: Start circling only in earliest obstacle distance.
292         # TODO: get rid of circle_in_map logic
293         circle_in_map = True
294         distance = 1
295         yx = YX(yx.y, yx.x)
296         #print('DEBUG CIRCLE_OUT', yx)
297         while circle_in_map:
298             if distance > self.fov_radius:
299                 break
300             circle_in_map = False
301             yx, _ = self.basic_circle_out_move(yx, 'RIGHT')
302             for dir_i in range(len(self.circle_out_directions)):
303                 for dir_progress in range(distance):
304                     direction = self.circle_out_directions[dir_i]
305                     yx, test = self.circle_out_move(yx, direction)
306                     if test:
307                         f(yx, distance, dir_i, dir_progress)
308                         circle_in_map = True
309             distance += 1
310
311
312
313 class FovMapHex(FovMap):
314     circle_out_directions = ('DOWNLEFT', 'LEFT', 'UPLEFT',
315                              'UPRIGHT', 'RIGHT', 'DOWNRIGHT')
316
317     def __init__(self, *args, **kwargs):
318         self.geometry = MapGeometryHex()
319         super().__init__(*args, **kwargs)
320
321     def circle_out_move(self, yx, direction):
322         return self.basic_circle_out_move(yx, direction)
323
324
325
326 class FovMapSquare(FovMap):
327     circle_out_directions = (('DOWN', 'LEFT'), ('LEFT', 'UP'),
328                              ('UP', 'RIGHT'), ('RIGHT', 'DOWN'))
329
330     def __init__(self, *args, **kwargs):
331         self.geometry = MapGeometrySquare()
332         super().__init__(*args, **kwargs)
333
334     def circle_out_move(self, yx, direction):
335         self.basic_circle_out_move(yx, direction[0])
336         return self.basic_circle_out_move(yx, direction[1])
337