home · contact · privacy
4f2f5f9e3b7c465bc05ed1409af9b318befb8d71
[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     @property
123     def size_i(self):
124         return self.size.y * self.size.x
125
126     def set_line(self, y, line):
127         height_map = self.size.y
128         width_map = self.size.x
129         if y >= height_map:
130             raise ArgError('too large row number %s' % y)
131         width_line = len(line)
132         if width_line != width_map:
133             raise ArgError('map line width %s unequal map width %s' % (width_line, width_map))
134         self.terrain = self.terrain[:y * width_map] + line +\
135                        self.terrain[(y + 1) * width_map:]
136
137     def get_position_index(self, yx):
138         return yx.y * self.size.x + yx.x
139
140     def lines(self):
141         width = self.size.x
142         for y in range(self.size.y):
143             yield (y, self.terrain[y * width:(y + 1) * width])
144
145
146
147 class FovMap(Map):
148
149     def __init__(self, source_map, center):
150         self.source_map = source_map
151         self.size = self.source_map.size
152         self.fov_radius = (self.size.y / 2) - 0.5
153         self.start_indented = True  #source_map.start_indented
154         self.terrain = '?' * self.size_i
155         self.center = center
156         self[self.center] = '.'
157         self.shadow_cones = []
158         self.geometry = self.geometry_class(self.size)
159         self.circle_out(self.center, self.shadow_process)
160
161     def shadow_process(self, yx, distance_to_center, dir_i, dir_progress):
162         # Possible optimization: If no shadow_cones yet and self[yx] == '.',
163         # skip all.
164         CIRCLE = 360  # Since we'll float anyways, number is actually arbitrary.
165
166         def correct_arm(arm):
167             if arm > CIRCLE:
168                 arm -= CIRCLE
169             return arm
170
171         def in_shadow_cone(new_cone):
172             for old_cone in self.shadow_cones:
173                 if old_cone[0] <= new_cone[0] and \
174                     new_cone[1] <= old_cone[1]:
175                     return True
176                 # We might want to also shade tiles whose middle arm is inside a
177                 # shadow cone for a darker FOV. Note that we then could not for
178                 # optimization purposes rely anymore on the assumption that a
179                 # shaded tile cannot add growth to existing shadow cones.
180             return False
181
182         def merge_cone(new_cone):
183             import math
184             for old_cone in self.shadow_cones:
185                 if new_cone[0] < old_cone[0] and \
186                     (new_cone[1] > old_cone[0] or
187                      math.isclose(new_cone[1], old_cone[0])):
188                     old_cone[0] = new_cone[0]
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                     old_cone[1] = new_cone[1]
194                     return True
195             return False
196
197         def eval_cone(cone):
198             if in_shadow_cone(cone):
199                 return
200             self[yx] = '.'
201             if self.source_map[yx] == 'X':
202                 unmerged = True
203                 while merge_cone(cone):
204                     unmerged = False
205                 if unmerged:
206                     self.shadow_cones += [cone]
207
208         step_size = (CIRCLE/len(self.circle_out_directions)) / distance_to_center
209         number_steps = dir_i * distance_to_center + dir_progress
210         left_arm = correct_arm(step_size/2 + step_size*number_steps)
211         right_arm = correct_arm(left_arm + step_size)
212
213         # Optimization potential: left cone could be derived from previous
214         # right cone. Better even: Precalculate all cones.
215         if right_arm < left_arm:
216             eval_cone([left_arm, CIRCLE])
217             eval_cone([0, right_arm])
218         else:
219             eval_cone([left_arm, right_arm])
220
221     def basic_circle_out_move(self, pos, direction):
222         """Move position pos into direction. Return whether still in map."""
223         mover = getattr(self.geometry, 'move_' + direction)
224         pos = mover(pos) #, self.start_indented)
225         if pos.y < 0 or pos.x < 0 or \
226             pos.y >= self.size.y or pos.x >= self.size.x:
227             return pos, False
228         return pos, True
229
230     def circle_out(self, yx, f):
231         # Optimization potential: Precalculate movement positions. (How to check
232         # circle_in_map then?)
233         # Optimization potential: Precalculate what tiles are shaded by what tile
234         # and skip evaluation of already shaded tile. (This only works if tiles
235         # shading implies they completely lie in existing shades; otherwise we
236         # would lose shade growth through tiles at shade borders.)
237         circle_in_map = True
238         distance = 1
239         yx = YX(yx.y, yx.x)
240         while circle_in_map:
241             if distance > self.fov_radius:
242                 break
243             circle_in_map = False
244             yx, _ = self.basic_circle_out_move(yx, 'RIGHT')
245             for dir_i in range(len(self.circle_out_directions)):
246                 for dir_progress in range(distance):
247                     direction = self.circle_out_directions[dir_i]
248                     yx, test = self.circle_out_move(yx, direction)
249                     if test:
250                         f(yx, distance, dir_i, dir_progress)
251                         circle_in_map = True
252             distance += 1
253
254
255
256 class FovMapHex(FovMap):
257     circle_out_directions = ('DOWNLEFT', 'LEFT', 'UPLEFT',
258                              'UPRIGHT', 'RIGHT', 'DOWNRIGHT')
259     geometry_class = MapGeometryHex
260
261     def circle_out_move(self, yx, direction):
262         return self.basic_circle_out_move(yx, direction)
263
264
265
266 class FovMapSquare(FovMap):
267     circle_out_directions = (('DOWN', 'LEFT'), ('LEFT', 'UP'),
268                              ('UP', 'RIGHT'), ('RIGHT', 'DOWN'))
269     geometry_class = MapGeometrySquare
270
271     def circle_out_move(self, yx, direction):
272         yx, _ = self.basic_circle_out_move(yx, direction[0])
273         return self.basic_circle_out_move(yx, direction[1])