home · contact · privacy
Refactor and extend new library.
[plomrogue2-experiments] / new / plomrogue / mapping.py
1 from plomrogue.errors import ArgError
2
3
4
5 class MapBase:
6
7     def __init__(self, size=(0, 0)):
8         self.size = size
9         self.terrain = '?'*self.size_i
10
11     @property
12     def size_i(self):
13         return self.size[0] * self.size[1]
14
15     def set_line(self, y, line):
16         height_map = self.size[0]
17         width_map = self.size[1]
18         if y >= height_map:
19             raise ArgError('too large row number %s' % y)
20         width_line = len(line)
21         if width_line > width_map:
22             raise ArgError('too large map line width %s' % width_line)
23         self.terrain = self.terrain[:y * width_map] + line +\
24                        self.terrain[(y + 1) * width_map:]
25
26     def get_position_index(self, yx):
27         return yx[0] * self.size[1] + yx[1]
28
29
30 class Map(MapBase):
31
32     def __getitem__(self, yx):
33         return self.terrain[self.get_position_index(yx)]
34
35     def __setitem__(self, yx, c):
36         pos_i = self.get_position_index(yx)
37         if type(c) == str:
38             self.terrain = self.terrain[:pos_i] + c + self.terrain[pos_i + 1:]
39         else:
40             self.terrain[pos_i] = c
41
42     def __iter__(self):
43         """Iterate over YX position coordinates."""
44         for y in range(self.size[0]):
45             for x in range(self.size[1]):
46                 yield [y, x]
47
48     def lines(self):
49         width = self.size[1]
50         for y in range(self.size[0]):
51             yield (y, self.terrain[y * width:(y + 1) * width])
52
53     def get_fov_map(self, yx):
54         return self.fov_map_type(self, yx)
55
56     def get_directions(self):
57         directions = []
58         for name in dir(self):
59             if name[:5] == 'move_':
60                 directions += [name[5:]]
61         return directions
62
63     def get_neighbors(self, pos):
64         neighbors = {}
65         if not hasattr(self, 'neighbors_to'):
66             self.neighbors_to = {}
67         if pos in self.neighbors_to:
68             return self.neighbors_to[pos]
69         for direction in self.get_directions():
70             neighbors[direction] = None
71             try:
72                 neighbors[direction] = self.move(pos, direction)
73             except GameError:
74                 pass
75         self.neighbors_to[pos] = neighbors
76         return neighbors
77
78     def new_from_shape(self, init_char):
79         import copy
80         new_map = copy.deepcopy(self)
81         for pos in new_map:
82             new_map[pos] = init_char
83         return new_map
84
85     def move(self, start_pos, direction):
86         mover = getattr(self, 'move_' + direction)
87         new_pos = mover(start_pos)
88         if new_pos[0] < 0 or new_pos[1] < 0 or \
89                 new_pos[0] >= self.size[0] or new_pos[1] >= self.size[1]:
90             raise GameError('would move outside map bounds')
91         return new_pos
92
93
94
95 class MapWithLeftRightMoves(Map):
96
97     def move_LEFT(self, start_pos):
98         return [start_pos[0], start_pos[1] - 1]
99
100     def move_RIGHT(self, start_pos):
101         return [start_pos[0], start_pos[1] + 1]
102
103
104
105 class MapSquare(MapWithLeftRightMoves):
106
107     def move_UP(self, start_pos):
108         return [start_pos[0] - 1, start_pos[1]]
109
110     def move_DOWN(self, start_pos):
111         return [start_pos[0] + 1, start_pos[1]]
112
113
114
115 class MapHex(MapWithLeftRightMoves):
116
117     def __init__(self, *args, **kwargs):
118         super().__init__(*args, **kwargs)
119         self.fov_map_type = FovMapHex
120
121     def move_UPLEFT(self, start_pos):
122         if start_pos[0] % 2 == 1:
123             return [start_pos[0] - 1, start_pos[1] - 1]
124         else:
125             return [start_pos[0] - 1, start_pos[1]]
126
127     def move_UPRIGHT(self, start_pos):
128         if start_pos[0] % 2 == 1:
129             return [start_pos[0] - 1, start_pos[1]]
130         else:
131             return [start_pos[0] - 1, start_pos[1] + 1]
132
133     def move_DOWNLEFT(self, start_pos):
134         if start_pos[0] % 2 == 1:
135              return [start_pos[0] + 1, start_pos[1] - 1]
136         else:
137                return [start_pos[0] + 1, start_pos[1]]
138
139     def move_DOWNRIGHT(self, start_pos):
140         if start_pos[0] % 2 == 1:
141             return [start_pos[0] + 1, start_pos[1]]
142         else:
143             return [start_pos[0] + 1, start_pos[1] + 1]
144
145
146
147 class FovMap:
148
149     def __init__(self, source_map, yx):
150         self.source_map = source_map
151         self.size = self.source_map.size
152         self.terrain = '?' * self.size_i
153         self[yx] = '.'
154         self.shadow_cones = []
155         self.circle_out(yx, self.shadow_process_hex)
156
157     def shadow_process_hex(self, yx, distance_to_center, dir_i, dir_progress):
158         # Possible optimization: If no shadow_cones yet and self[yx] == '.',
159         # skip all.
160         CIRCLE = 360  # Since we'll float anyways, number is actually arbitrary.
161
162         def correct_arm(arm):
163             if arm < 0:
164                 arm += CIRCLE
165             return arm
166
167         def in_shadow_cone(new_cone):
168             for old_cone in self.shadow_cones:
169                 if old_cone[0] >= new_cone[0] and \
170                     new_cone[1] >= old_cone[1]:
171                     #print('DEBUG shadowed by:', old_cone)
172                     return True
173                 # We might want to also shade hexes whose middle arm is inside a
174                 # shadow cone for a darker FOV. Note that we then could not for
175                 # optimization purposes rely anymore on the assumption that a
176                 # shaded hex cannot add growth to existing shadow cones.
177             return False
178
179         def merge_cone(new_cone):
180             import math
181             for old_cone in self.shadow_cones:
182                 if new_cone[0] > old_cone[0] and \
183                     (new_cone[1] < old_cone[0] or
184                      math.isclose(new_cone[1], old_cone[0])):
185                     #print('DEBUG merging to', old_cone)
186                     old_cone[0] = new_cone[0]
187                     #print('DEBUG merged cone:', old_cone)
188                     return True
189                 if new_cone[1] < old_cone[1] and \
190                     (new_cone[0] > old_cone[1] or
191                      math.isclose(new_cone[0], old_cone[1])):
192                     #print('DEBUG merging to', old_cone)
193                     old_cone[1] = new_cone[1]
194                     #print('DEBUG merged cone:', old_cone)
195                     return True
196             return False
197
198         def eval_cone(cone):
199             #print('DEBUG CONE', cone, '(', step_size, distance_to_center, number_steps, ')')
200             if in_shadow_cone(cone):
201                 return
202             self[yx] = '.'
203             if self.source_map[yx] != '.':
204                 #print('DEBUG throws shadow', cone)
205                 unmerged = True
206                 while merge_cone(cone):
207                     unmerged = False
208                 if unmerged:
209                     self.shadow_cones += [cone]
210
211         #print('DEBUG', yx)
212         step_size = (CIRCLE/len(self.circle_out_directions)) / distance_to_center
213         number_steps = dir_i * distance_to_center + dir_progress
214         left_arm = correct_arm(-(step_size/2) - step_size*number_steps)
215         right_arm = correct_arm(left_arm - step_size)
216         # Optimization potential: left cone could be derived from previous
217         # right cone. Better even: Precalculate all cones.
218         if right_arm > left_arm:
219             eval_cone([left_arm, 0])
220             eval_cone([CIRCLE, right_arm])
221         else:
222             eval_cone([left_arm, right_arm])
223
224     def basic_circle_out_move(self, pos, direction):
225         """Move position pos into direction. Return whether still in map."""
226         mover = getattr(self, 'move_' + direction)
227         pos[:] = mover(pos)
228         if pos[0] < 0 or pos[1] < 0 or \
229             pos[0] >= self.size[0] or pos[1] >= self.size[1]:
230             return False
231         return True
232
233     def circle_out(self, yx, f):
234         # Optimization potential: Precalculate movement positions. (How to check
235         # circle_in_map then?)
236         # Optimization potential: Precalculate what hexes are shaded by what hex
237         # and skip evaluation of already shaded hexes. (This only works if hex
238         # shading implies they completely lie in existing shades; otherwise we
239         # would lose shade growth through hexes at shade borders.)
240
241         # TODO: Start circling only in earliest obstacle distance.
242         circle_in_map = True
243         distance = 1
244         yx = yx[:]
245         #print('DEBUG CIRCLE_OUT', yx)
246         while circle_in_map:
247             circle_in_map = False
248             self.basic_circle_out_move(yx, 'RIGHT')
249             for dir_i in range(len(self.circle_out_directions)):
250                 for dir_progress in range(distance):
251                     direction = self.circle_out_directions[dir_i]
252                     if self.circle_out_move(yx, direction):
253                         f(yx, distance, dir_i, dir_progress)
254                         circle_in_map = True
255             distance += 1
256
257
258
259 class FovMapHex(FovMap, MapHex):
260     circle_out_directions = ('DOWNLEFT', 'LEFT', 'UPLEFT',
261                              'UPRIGHT', 'RIGHT', 'DOWNRIGHT')
262
263     def circle_out_move(self, yx, direction):
264         return self.basic_circle_out_move(yx, direction)
265
266
267
268 class FovMapSquare(FovMap, MapSquare):
269     circle_out_directions = (('DOWN', 'LEFT'), ('LEFT', 'UP'),
270                              ('UP', 'RIGHT'), ('RIGHT', 'DOWN'))
271
272     def circle_out_move(self, yx, direction):
273         self.basic_circle_out_move(yx, direction[0])
274         return self.basic_circle_out_move(yx, direction[1])