home · contact · privacy
Use tuples for positions; fix inventory saving bug.
[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         pos = tuple(pos)
66         if not hasattr(self, 'neighbors_to'):
67             self.neighbors_to = {}
68         if pos in self.neighbors_to:
69             return self.neighbors_to[pos]
70         for direction in self.get_directions():
71             neighbors[direction] = None
72             try:
73                 neighbors[direction] = self.move(pos, direction)
74             except GameError:
75                 pass
76         self.neighbors_to[pos] = neighbors
77         return neighbors
78
79     def new_from_shape(self, init_char):
80         import copy
81         new_map = copy.deepcopy(self)
82         for pos in new_map:
83             new_map[pos] = init_char
84         return new_map
85
86     def move(self, start_pos, direction):
87         mover = getattr(self, 'move_' + direction)
88         new_pos = mover(start_pos)
89         if new_pos[0] < 0 or new_pos[1] < 0 or \
90                 new_pos[0] >= self.size[0] or new_pos[1] >= self.size[1]:
91             raise GameError('would move outside map bounds')
92         return new_pos
93
94
95
96 class MapWithLeftRightMoves(Map):
97
98     def move_LEFT(self, start_pos):
99         return (start_pos[0], start_pos[1] - 1)
100
101     def move_RIGHT(self, start_pos):
102         return (start_pos[0], start_pos[1] + 1)
103
104
105
106 class MapSquare(MapWithLeftRightMoves):
107
108     def move_UP(self, start_pos):
109         return (start_pos[0] - 1, start_pos[1])
110
111     def move_DOWN(self, start_pos):
112         return (start_pos[0] + 1, start_pos[1])
113
114
115
116 class MapHex(MapWithLeftRightMoves):
117
118     def __init__(self, *args, **kwargs):
119         super().__init__(*args, **kwargs)
120         self.fov_map_type = FovMapHex
121
122     def move_UPLEFT(self, start_pos):
123         if start_pos[0] % 2 == 1:
124             return (start_pos[0] - 1, start_pos[1] - 1)
125         else:
126             return (start_pos[0] - 1, start_pos[1])
127
128     def move_UPRIGHT(self, start_pos):
129         if start_pos[0] % 2 == 1:
130             return (start_pos[0] - 1, start_pos[1])
131         else:
132             return (start_pos[0] - 1, start_pos[1] + 1)
133
134     def move_DOWNLEFT(self, start_pos):
135         if start_pos[0] % 2 == 1:
136              return (start_pos[0] + 1, start_pos[1] - 1)
137         else:
138                return (start_pos[0] + 1, start_pos[1])
139
140     def move_DOWNRIGHT(self, start_pos):
141         if start_pos[0] % 2 == 1:
142             return (start_pos[0] + 1, start_pos[1])
143         else:
144             return (start_pos[0] + 1, start_pos[1] + 1)
145
146
147
148 class FovMap:
149
150     def __init__(self, source_map, yx):
151         self.source_map = source_map
152         self.size = self.source_map.size
153         self.terrain = '?' * self.size_i
154         self[yx] = '.'
155         self.shadow_cones = []
156         self.circle_out(yx, self.shadow_process_hex)
157
158     def shadow_process_hex(self, yx, distance_to_center, dir_i, dir_progress):
159         # Possible optimization: If no shadow_cones yet and self[yx] == '.',
160         # skip all.
161         CIRCLE = 360  # Since we'll float anyways, number is actually arbitrary.
162
163         def correct_arm(arm):
164             if arm < 0:
165                 arm += CIRCLE
166             return arm
167
168         def in_shadow_cone(new_cone):
169             for old_cone in self.shadow_cones:
170                 if old_cone[0] >= new_cone[0] and \
171                     new_cone[1] >= old_cone[1]:
172                     #print('DEBUG shadowed by:', old_cone)
173                     return True
174                 # We might want to also shade hexes whose middle arm is inside a
175                 # shadow cone for a darker FOV. Note that we then could not for
176                 # optimization purposes rely anymore on the assumption that a
177                 # shaded hex cannot add growth to existing shadow cones.
178             return False
179
180         def merge_cone(new_cone):
181             import math
182             for old_cone in self.shadow_cones:
183                 if new_cone[0] > old_cone[0] and \
184                     (new_cone[1] < old_cone[0] or
185                      math.isclose(new_cone[1], old_cone[0])):
186                     #print('DEBUG merging to', old_cone)
187                     old_cone[0] = new_cone[0]
188                     #print('DEBUG merged cone:', old_cone)
189                     return True
190                 if new_cone[1] < old_cone[1] and \
191                     (new_cone[0] > old_cone[1] or
192                      math.isclose(new_cone[0], old_cone[1])):
193                     #print('DEBUG merging to', old_cone)
194                     old_cone[1] = new_cone[1]
195                     #print('DEBUG merged cone:', old_cone)
196                     return True
197             return False
198
199         def eval_cone(cone):
200             #print('DEBUG CONE', cone, '(', step_size, distance_to_center, number_steps, ')')
201             if in_shadow_cone(cone):
202                 return
203             self[yx] = '.'
204             if self.source_map[yx] != '.':
205                 #print('DEBUG throws shadow', cone)
206                 unmerged = True
207                 while merge_cone(cone):
208                     unmerged = False
209                 if unmerged:
210                     self.shadow_cones += [cone]
211
212         #print('DEBUG', yx)
213         step_size = (CIRCLE/len(self.circle_out_directions)) / distance_to_center
214         number_steps = dir_i * distance_to_center + dir_progress
215         left_arm = correct_arm(-(step_size/2) - step_size*number_steps)
216         right_arm = correct_arm(left_arm - step_size)
217         # Optimization potential: left cone could be derived from previous
218         # right cone. Better even: Precalculate all cones.
219         if right_arm > left_arm:
220             eval_cone([left_arm, 0])
221             eval_cone([CIRCLE, right_arm])
222         else:
223             eval_cone([left_arm, right_arm])
224
225     def basic_circle_out_move(self, pos, direction):
226         """Move position pos into direction. Return whether still in map."""
227         mover = getattr(self, 'move_' + direction)
228         pos = mover(pos)
229         if pos[0] < 0 or pos[1] < 0 or \
230             pos[0] >= self.size[0] or pos[1] >= self.size[1]:
231             return pos, False
232         return pos, True
233
234     def circle_out(self, yx, f):
235         # Optimization potential: Precalculate movement positions. (How to check
236         # circle_in_map then?)
237         # Optimization potential: Precalculate what hexes are shaded by what hex
238         # and skip evaluation of already shaded hexes. (This only works if hex
239         # shading implies they completely lie in existing shades; otherwise we
240         # would lose shade growth through hexes at shade borders.)
241
242         # TODO: Start circling only in earliest obstacle distance.
243         circle_in_map = True
244         distance = 1
245         yx = yx[:]
246         #print('DEBUG CIRCLE_OUT', yx)
247         while circle_in_map:
248             circle_in_map = False
249             yx, _ = self.basic_circle_out_move(yx, 'RIGHT')
250             for dir_i in range(len(self.circle_out_directions)):
251                 for dir_progress in range(distance):
252                     direction = self.circle_out_directions[dir_i]
253                     yx, test = self.circle_out_move(yx, direction)
254                     if test:
255                         f(yx, distance, dir_i, dir_progress)
256                         circle_in_map = True
257             distance += 1
258
259
260
261 class FovMapHex(FovMap, MapHex):
262     circle_out_directions = ('DOWNLEFT', 'LEFT', 'UPLEFT',
263                              'UPRIGHT', 'RIGHT', 'DOWNRIGHT')
264
265     def circle_out_move(self, yx, direction):
266         return self.basic_circle_out_move(yx, direction)
267
268
269
270 class FovMapSquare(FovMap, MapSquare):
271     circle_out_directions = (('DOWN', 'LEFT'), ('LEFT', 'UP'),
272                              ('UP', 'RIGHT'), ('RIGHT', 'DOWN'))
273
274     def circle_out_move(self, yx, direction):
275         self.basic_circle_out_move(yx, direction[0])
276         return self.basic_circle_out_move(yx, direction[1])