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