1 from plomrogue.errors import ArgError
6 class YX(collections.namedtuple('YX', ('y', 'x'))):
8 def __add__(self, other):
9 return YX(self.y + other.y, self.x + other.x)
11 def __sub__(self, other):
12 return YX(self.y - other.y, self.x - other.x)
15 return 'Y:%s,X:%s' % (self.y, self.x)
21 def __init__(self, size=YX(0, 0), init_char = '?', start_indented=True):
23 self.terrain = init_char*self.size_i
24 self.start_indented = start_indented
25 self.awake = 100 # asleep if zero
28 def __getitem__(self, yx):
29 return self.terrain[self.get_position_index(yx)]
31 def __setitem__(self, yx, c):
32 pos_i = self.get_position_index(yx)
34 self.terrain = self.terrain[:pos_i] + c + self.terrain[pos_i + 1:]
36 self.terrain[pos_i] = c
39 """Iterate over YX position coordinates."""
40 for y in range(self.size.y):
41 for x in range(self.size.x):
46 return self.size.y * self.size.x
48 def set_line(self, y, line):
49 height_map = self.size.y
50 width_map = self.size.x
52 raise ArgError('too large row number %s' % y)
53 width_line = len(line)
54 if width_line > width_map:
55 raise ArgError('too large map line width %s' % width_line)
56 self.terrain = self.terrain[:y * width_map] + line +\
57 self.terrain[(y + 1) * width_map:]
59 def get_position_index(self, yx):
60 return yx.y * self.size.x + yx.x
64 for y in range(self.size.y):
65 yield (y, self.terrain[y * width:(y + 1) * width])
71 def get_directions(self):
73 for name in dir(self):
74 if name[:5] == 'move_':
75 directions += [name[5:]]
78 def get_neighbors(self, pos, map_size, start_indented=True):
80 if not hasattr(self, 'neighbors_to'):
81 self.neighbors_to = {}
82 if not map_size in self.neighbors_to:
83 self.neighbors_to[map_size] = {}
84 if not start_indented in self.neighbors_to[map_size]:
85 self.neighbors_to[map_size][start_indented] = {}
86 if pos in self.neighbors_to[map_size][start_indented]:
87 return self.neighbors_to[map_size][start_indented][pos]
88 for direction in self.get_directions():
89 neighbors[direction] = self.move(pos, direction, map_size,
91 self.neighbors_to[map_size][start_indented][pos] = neighbors
94 def undouble_coordinate(self, maps_size, coordinate):
95 y = maps_size.y * coordinate[0].y + coordinate[1].y
96 x = maps_size.x * coordinate[0].x + coordinate[1].x
99 def get_view_offset(self, maps_size, center, radius):
100 yx_to_origin = self.undouble_coordinate(maps_size, center)
101 return yx_to_origin - YX(radius, radius)
103 def pos_in_view(self, pos, offset, maps_size):
104 return self.undouble_coordinate(maps_size, pos) - offset
106 def get_view_and_seen_maps(self, maps_size, get_map, radius, view_offset):
107 m = Map(size=YX(radius*2+1, radius*2+1),
108 start_indented=(view_offset.y % 2 == 0))
111 seen_pos = self.correct_double_coordinate(maps_size, (0,0),
113 if seen_pos[0] not in seen_maps:
114 seen_maps += [seen_pos[0]]
115 seen_map = get_map(seen_pos[0])
117 seen_map = Map(size=maps_size)
118 m[pos] = seen_map[seen_pos[1]]
121 def correct_double_coordinate(self, map_size, big_yx, little_yx):
123 def adapt_axis(axis):
124 maps_crossed = little_yx[axis] // map_size[axis]
125 new_big = big_yx[axis] + maps_crossed
126 new_little = little_yx[axis] % map_size[axis]
127 return new_big, new_little
129 new_big_y, new_little_y = adapt_axis(0)
130 new_big_x, new_little_x = adapt_axis(1)
131 return YX(new_big_y, new_big_x), YX(new_little_y, new_little_x)
133 def move(self, start_pos, direction, map_size, start_indented=True):
134 mover = getattr(self, 'move_' + direction)
135 big_yx, little_yx = start_pos
136 uncorrected_target = mover(little_yx, start_indented)
137 return self.correct_double_coordinate(map_size, big_yx,
142 class MapGeometryWithLeftRightMoves(MapGeometry):
144 def move_LEFT(self, start_pos, _):
145 return YX(start_pos.y, start_pos.x - 1)
147 def move_RIGHT(self, start_pos, _):
148 return YX(start_pos.y, start_pos.x + 1)
152 class MapGeometrySquare(MapGeometryWithLeftRightMoves):
154 def move_UP(self, start_pos, _):
155 return YX(start_pos.y - 1, start_pos.x)
157 def move_DOWN(self, start_pos, _):
158 return YX(start_pos.y + 1, start_pos.x)
162 class MapGeometryHex(MapGeometryWithLeftRightMoves):
164 def __init__(self, *args, **kwargs):
165 super().__init__(*args, **kwargs)
166 self.fov_map_type = FovMapHex
168 def move_UPLEFT(self, start_pos, start_indented):
169 if start_pos.y % 2 == start_indented:
170 return YX(start_pos.y - 1, start_pos.x - 1)
172 return YX(start_pos.y - 1, start_pos.x)
174 def move_UPRIGHT(self, start_pos, start_indented):
175 if start_pos.y % 2 == start_indented:
176 return YX(start_pos.y - 1, start_pos.x)
178 return YX(start_pos.y - 1, start_pos.x + 1)
180 def move_DOWNLEFT(self, start_pos, start_indented):
181 if start_pos.y % 2 == start_indented:
182 return YX(start_pos.y + 1, start_pos.x - 1)
184 return YX(start_pos.y + 1, start_pos.x)
186 def move_DOWNRIGHT(self, start_pos, start_indented):
187 if start_pos.y % 2 == start_indented:
188 return YX(start_pos.y + 1, start_pos.x)
190 return YX(start_pos.y + 1, start_pos.x + 1)
196 def __init__(self, source_map, center):
197 self.source_map = source_map
198 self.size = self.source_map.size
199 self.fov_radius = (self.size.y / 2) - 0.5
200 self.start_indented = source_map.start_indented
201 self.terrain = '?' * self.size_i
203 self.shadow_cones = []
204 self.circle_out(center, self.shadow_process_hex)
206 def shadow_process_hex(self, yx, distance_to_center, dir_i, dir_progress):
207 # Possible optimization: If no shadow_cones yet and self[yx] == '.',
209 CIRCLE = 360 # Since we'll float anyways, number is actually arbitrary.
211 def correct_arm(arm):
216 def in_shadow_cone(new_cone):
217 for old_cone in self.shadow_cones:
218 if old_cone[0] >= new_cone[0] and \
219 new_cone[1] >= old_cone[1]:
220 #print('DEBUG shadowed by:', old_cone)
222 # We might want to also shade hexes whose middle arm is inside a
223 # shadow cone for a darker FOV. Note that we then could not for
224 # optimization purposes rely anymore on the assumption that a
225 # shaded hex cannot add growth to existing shadow cones.
228 def merge_cone(new_cone):
230 for old_cone in self.shadow_cones:
231 if new_cone[0] > old_cone[0] and \
232 (new_cone[1] < old_cone[0] or
233 math.isclose(new_cone[1], old_cone[0])):
234 #print('DEBUG merging to', old_cone)
235 old_cone[0] = new_cone[0]
236 #print('DEBUG merged cone:', old_cone)
238 if new_cone[1] < old_cone[1] and \
239 (new_cone[0] > old_cone[1] or
240 math.isclose(new_cone[0], old_cone[1])):
241 #print('DEBUG merging to', old_cone)
242 old_cone[1] = new_cone[1]
243 #print('DEBUG merged cone:', old_cone)
248 #print('DEBUG CONE', cone, '(', step_size, distance_to_center, number_steps, ')')
249 if in_shadow_cone(cone):
252 if self.source_map[yx] != '.':
253 #print('DEBUG throws shadow', cone)
255 while merge_cone(cone):
258 self.shadow_cones += [cone]
261 step_size = (CIRCLE/len(self.circle_out_directions)) / distance_to_center
262 number_steps = dir_i * distance_to_center + dir_progress
263 left_arm = correct_arm(-(step_size/2) - step_size*number_steps)
264 right_arm = correct_arm(left_arm - step_size)
265 # Optimization potential: left cone could be derived from previous
266 # right cone. Better even: Precalculate all cones.
267 if right_arm > left_arm:
268 eval_cone([left_arm, 0])
269 eval_cone([CIRCLE, right_arm])
271 eval_cone([left_arm, right_arm])
273 def basic_circle_out_move(self, pos, direction):
274 """Move position pos into direction. Return whether still in map."""
275 mover = getattr(self.geometry, 'move_' + direction)
276 pos = mover(pos, self.start_indented)
277 if pos.y < 0 or pos.x < 0 or \
278 pos.y >= self.size.y or pos.x >= self.size.x:
282 def circle_out(self, yx, f):
283 # Optimization potential: Precalculate movement positions. (How to check
284 # circle_in_map then?)
285 # Optimization potential: Precalculate what hexes are shaded by what hex
286 # and skip evaluation of already shaded hexes. (This only works if hex
287 # shading implies they completely lie in existing shades; otherwise we
288 # would lose shade growth through hexes at shade borders.)
290 # TODO: Start circling only in earliest obstacle distance.
291 # TODO: get rid of circle_in_map logic
295 #print('DEBUG CIRCLE_OUT', yx)
297 if distance > self.fov_radius:
299 circle_in_map = False
300 yx, _ = self.basic_circle_out_move(yx, 'RIGHT')
301 for dir_i in range(len(self.circle_out_directions)):
302 for dir_progress in range(distance):
303 direction = self.circle_out_directions[dir_i]
304 yx, test = self.circle_out_move(yx, direction)
306 f(yx, distance, dir_i, dir_progress)
312 class FovMapHex(FovMap):
313 circle_out_directions = ('DOWNLEFT', 'LEFT', 'UPLEFT',
314 'UPRIGHT', 'RIGHT', 'DOWNRIGHT')
316 def __init__(self, *args, **kwargs):
317 self.geometry = MapGeometryHex()
318 super().__init__(*args, **kwargs)
320 def circle_out_move(self, yx, direction):
321 return self.basic_circle_out_move(yx, direction)
325 class FovMapSquare(FovMap):
326 circle_out_directions = (('DOWN', 'LEFT'), ('LEFT', 'UP'),
327 ('UP', 'RIGHT'), ('RIGHT', 'DOWN'))
329 def __init__(self, *args, **kwargs):
330 self.geometry = MapGeometrySquare()
331 super().__init__(*args, **kwargs)
333 def circle_out_move(self, yx, direction):
334 self.basic_circle_out_move(yx, direction[0])
335 return self.basic_circle_out_move(yx, direction[1])