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