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