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