# A Python 3 and 2 Pathfinder with Pygame Example

by James Spencer

Originally my Roguelike had a pathfinder that predated me even starting to write a Roguelike. It suffered badly from being both my first serious pathfinder and some of my earliest Python code. Layer on a raft of incremental additions, and it got complicated and weird, and well, it had to go. I intend to use this pathfinder as a base for any personal Python project that requires pathfinder. I designed this pathfinder to take advantage of the similarities between A-Star and Dijkstra pathfinding, while leveraging the high level nature of Python to make the actual search functions as simple and pseudocode like as possible. This implementation is designed to work on grid based worlds (with the concept of distance as opposed to steps), though extending it to work with hex based worlds would be trivial. It is intended to be minimal and comprehensible, and doesn't include any provisions for variable movement costs though they would be easy to add.

Secondly, let me make it clear that this is not intended as a tutorial on A-Star pathfinding or Dijkstra pathfinding, it is intended as a pure python pathfinder that is: 1) drop in ready, 2) easily modifiable, and 3) fast enough.

If you are interested in tutorials on pathfinding I would suggest:

The Pathfinder(Area()) class has four public functions:

1. find_point(self, x1, y1, x2, y2, use_diagonals=True, best_path=True, abort=False)
2. is_point_findable(self, x1, y1, x2, y2, use_diagonals=True, abort=False)
3. find_tile(self, x1, y1, tile, use_diagonals=True, best_path=True, abort=False)
4. nearest(self, x1, y1, tile, use_diagonals=True, abort=False)

All of these functions are documented in the code. In short, 'find_point()' will return deque() with a path from x1, y1 to x2, y2 (or None if no path is found), 'is_point_findable()' will return a Boolean if a point can be found, 'find_tile()' will return deque() with a path from x1, y1 to the nearest tile (or tile in an iterable of tiles) as specified by 'tile' (or None if no path is found), and finally 'nearest()' will look for a tile (or tile in an iterable of tiles) and return a Tuple of '(x, y, tile name)' (or None if no tile is found).

Both 'find_point()' and 'is_point_findable()' use an A-Star search, while 'find_tile()' and 'nearest()' use a Dijkstra search. As was mentioned this implementation is designed for grid based worlds, and is distance aware, meaning that it will generate paths based on the shortest distance as opposed to the fewest steps. While largely moot for cardinal only movement, this does have implications when diagonal movement is allowed (use_diagonals == True).

Pathfinder Implementation Notes:

• The actual pathfinder only requires Python, and the example requires Python and Pygame. Pygame should be installable via 'pip'.
• The pathfinder expects an 'Area()' class where: 'area.terrain' is a list of lists of terrain names (like a 2D array), 'area.width' is the width of a rectangular area, and 'area.height' is the height of a rectangular area.
• The pathfinder expects a 'config.OBSTRUCTION_CHARACTERS' set / tuple / list, where the members are tiles that can't be pathed through. This could also be dictionary where the keys are the tiles that can't be pathed through, and the values can be whatever you want (with good ideas being the character representation of the tile or a Pygame surface with the tile's graphic).
• The pathfinder is designed to be flexible. Thus setting 'self._directions' makes it easy to choose between searching cardinal directions versus searching cardinal and diagonal directions, setting 'self._heuristic' makes it easy to do a Dijkstra search ('self._heuristic == None') or to assign an appropriate heuristic for and A-Star search, and setting 'self._is_goal' lets you discriminate goals that are points, tiles, or a tile in an iterable of tiles.
• The pathfinder internally has 'self._closed_set_parent_map' and 'self._closed_set_coords', and 'self._open_set' and 'self._open_set_coords'. This is Python specific. Testing for inclusion in a set in Python is fast necessitating the use of 'self._closed_set_coords' and 'self._open_set_coords'. Meanwhile Python's heapq wants hashable objects to sort necessitating 'self._open_set'.
• 'self._closed_set_parent_map' is a list of lists that is set to 'None' unless a tile has a parent that leads to the origin of a search, then it has an (x, y) Tuple of the parent's coordinates. This is basically a Dijkstra map, and is used to help efficiently retrace the path.
• The ordering of the sub-lists in 'self._open_set' should break ties in a desirable manner for A-Star searches.
• Setting 'self._print_path_info = True' will print info about a found path from '_retrace_path' to the console.
• If you want to implement variable movement costs is should be trivial if you modify '_look_for_open' at about Line 240. A 1.0 based movement system, where 1.0 is the the fastest possible movement for any given tile, and where slower terrains have a higher modifier (1.1, 1.3, etc.), should be relatively straightforward to implement.
• if '._unobstruct_goals == True' then a goal (point, tile, iterable of tiles) will be found even if it is an obstruction. This is set to 'False' for 'find_point' and 'is_point_findable' and 'True' for 'find_tile' and 'nearest' under the assumption that if you're specifically looking for an obstruction you probably want to find it.

Example Implementation Notes:

• Since the example doesn't bundle a font it looks for: "dejavusansmono", "liberationmono", "andalemono", "lucidamono", "notomono", and finally the first font with 'mono' in the name. If the display is hideous a list of fonts with mono in the name is printed to the console. Add a reasonable choice from that list to 'font_names' (Line 691).
• The example times 5 functions by default, and colours the paths / found tiles. '|R Path' is the red path, '|G Path' the green path, '|B Path' is the blue path, and '|F Path' is the fuchsia (which by default is looking for the nearest 'open secret door' and not a path). The relevant code starts on Line 788 and should be easy to modify.

Image of the Pygame Example:

Thoughts on Performance:

There is 1 unavoidable fact about this pathfinder: it's written in Python and not C. While it aims to be efficient Python, it will be considerably slower than any reasonable C implementation. With that being said, I don't consider it too slow for a traditional roguelike or most other turn based games, and it does bring to the table all of the advantages Python has to offer.

There are steps developers can take to mitigate any excessive slowness in this implementation. In rough order of preference (with 1-6 being reasonable, and 7-10 being more heavy handed, IMHO):

1. Avoid recalculating paths. Both 'find_point' and 'find_tile' return a deque of (x, y) Tuples. Don't recalculate every step, just validate the next step (or maybe a few steps ahead for smarter creatures). Python's deque has a fast '.popleft()' that should come in handy for path consumers.
2. Do you need to use diagonal movement? If not you'll get a > 40% speedup with 'use_diagonals=False'. Do you need the best path? If not you get a < 10% speedup with 'best_path=False'. If 'best_path == False' paths will tend to veer slightly toward the goal. This may actually be desirable for more organic looking paths.
3. Do you still need diagonal movement and the best path when both the player and a creature can't see each other?
4. Can more of your creatures be at rest until the player comes into view?
5. Can you limit searches to a certain "as the crow flies" distance?
6. It would be easy to make a function that produces Dijkstra maps of a given area to ANY given point. You could use these Dijkstra maps as pre-calculated paths fixed to waypoints.
7. Can you make maps that are less twisty, maze like, and / or with fewer culs-de-sac?
8. 'abort=' can be set to stop a long search based on the size of the '._closed_set_coords'.
9. Even without multiprocessing it would be relatively easy to write '_find_path_bipolar' and a 'find_point_bipolar' that searches from the start to the goal and the goal to the start. Such a search would terminate when the goal is found, or when they share an entry in the closed set. Given how an A-Star frontier expands, even without multiprocessing, it should help reduce then number of bad paths explored in maps that are twisty, maze like, and / or have culs-de-sac.
10. You could leverage Python's 'multiprocessing' module and have one or more processes dedicated to calculating paths while you're game's main process continues on with other work until paths are calculated. Use this to pre-calculate paths where possible.

Pastebin Link to the Code:

Note: The Pastebin link has rather better code highlighting.

The Full Code Follows Below:

1. `#! /usr/bin/env python3`
2. `# coding: utf-8`
3. ` `
4. `# pathfinder.py, a python pathfinder and demo by`
5. `# James Spencer <jamessp [at] gmail.com>.`
6. ` `
7. `# To the extent possible under law, the person who associated CC0 with`
8. `# pathfinder.py has waived all copyright and related or neighboring rights`
9. `# to pathfinder.py.`
10. ` `
11. `# You should have received a copy of the CC0 legalcode along with this`
12. `# work. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.`
13. ` `
14. `from __future__ import print_function`
15. `from __future__ import division`
16. `from __future__ import unicode_literals`
17. `from collections import deque`
18. `import heapq`
19. `from sys import version_info`
20. ` `
21. ` `
22. `if version_info[0] < 3:`
23. `        range = xrange`
24. ` `
25. ` `
26. `class Config(object):`
27. `    '''This class is a minimal subset of <config.py> from my project, and much`
28. `    of the data herein was parsed from config files, hence the irregular`
29. `    naming. Feel free top plop the dicts into a <config.py> of your own and`
30. `    import it.`
31. `    '''`
32. ` `
33. `    def __init__(self):`
34. `        self.TERRAIN_CHARACTERS = {'open secret door'   : '~',`
35. `                                   'closed secret door' : '§',`
36. `                                   'flagstone'          : '.',`
37. `                                   'stone brick'        : '#',`
38. `                                   'closed door'        : '+',`
39. `                                   'open door'          : '-',`
40. `                                   'solid stone'        : '&'}`
41. `        self.TERRAIN_COLORS = {'closed door'        : 'aqua',`
42. `                               'flagstone'          : 'silver',`
43. `                               'open secret door'   : 'aqua',`
44. `                               'open door'          : 'aqua',`
45. `                               'solid stone'        : 'black',`
46. `                               'stone brick'        : 'white',`
47. `                               'closed secret door' : 'aqua'}`
48. `        # NOTE: This could easily be a dict where the keys are the obstructions`
49. `        # and the values are the tile characters, pygame surfaces, etc.`
50. `        self.OBSTRUCTION_CHARACTERS = {'closed secret door', 'stone brick',`
51. `                                       'closed door', 'solid stone'}`
52. `        # 16 of the DB32 colors, as they are easier on the eyes than VGA16.`
53. `        self.COLORNAMES = {'white':   (255, 255, 255),`
54. `                           'yellow':  (251, 242, 54),`
55. `                           'fuchsia': (215, 123, 186),`
56. `                           'red':     (172, 50, 50),`
57. `                           'silver':  (155, 173, 183),`
58. `                           'gray':    (105, 106, 106),`
59. `                           'olive':   (143, 151, 74),`
60. `                           'purple':  (118, 66, 138),`
61. `                           'maroon':  (102, 57, 49),`
62. `                           'aqua':    (96, 205, 228),`
63. `                           'lime':    (153, 229, 80),`
64. `                           'teal':    (48, 96, 130),`
65. `                           'green':   (75, 105, 47),`
66. `                           'blue':    (91, 110, 225),`
67. `                           'navy':    (63, 63, 116),`
68. `                           'black':   (0, 0, 0)}`
69. ` `
70. ` `
71. `# To 'fake' my projects <config.py>`
72. `config = Config()`
73. ` `
74. ` `
75. `class Area(object):`
76. `        '''The relevant to pathfinding bits of my project's Area() class. See`
77. `        the example at the end to see how this is used.`
78. `        '''`
79. ` `
80. `        def __init__(self):`
81. `            self.terrain = None`
82. `            self.width = None`
83. `            self.height = None`
84. ` `
85. ` `
86. `class Pathfinder(object):`
87. `    '''Find a path form x1, y1 to a point or tile(s).`
88. ` `
89. `    area -- An instance of the Area() class. See Area() at the top, and the`
90. `    pygame example at the end of the file for a minimal implementation.`
91. `    c_dist -- Integer or Float, the distance of a step in a cardinal`
92. `    direction.`
93. `    d_dist -- Integer or Float, the distance of a step in a diagonal`
94. `    direction.`
95. `    obstruction_characters -- An iterable of characters that obstruct movement.`
96. `    '''`
97. ` `
98. `    def __init__(self, area):`
99. `        self.area = area    # An instance of the Area() class.`
100. `        self.c_dist = 70    # Could be 70, 1.0,                10, 100, 1000.`
101. `        self.d_dist = 99    # Could be 99, 1.4142135623730951, 14, 141, 1414.`
102. `        self.obstruction_characters = config.OBSTRUCTION_CHARACTERS`
103. `        self._unobstruct_goals = None    # Find a goal that is an obstruction.`
104. `        self._cardinals = [( 0, -1, self.c_dist), ( 1,  0, self.c_dist),`
105. `                           ( 0,  1, self.c_dist), (-1,  0, self.c_dist)]`
106. `        self._diagonals = [(-1, -1, self.d_dist), ( 1, -1, self.d_dist),`
107. `                           ( 1,  1, self.d_dist), (-1,  1, self.d_dist)]`
108. `        self._directions = None          # Cardinals, or cardinals + diagonals.`
109. `        self._heuristic = None           # The A-Star heuristic`
110. `        self._x2, self._y2 = None, None  # Used if the goal is a point.`
111. `        self._tile, self._tiles = None, None         # goal is a tile, tiles.`
112. `        self._closed_set_coords = set()  # Just the coords to speed up checks.`
113. `        # List of lists of parent coordinates to help retrace the path.`
114. `        # NOTE: This is a literal Dijkstra map. See ._purge_private() for info.`
115. `        self.__parent_map_row = [None] * self.area.width`
116. `        self._closed_set_parent_map = []`
117. `        self._open_set = []             # Tiles to be evaluated.`
118. `        self._open_set_coords = set()   # Just the coords to speed up checks.`
119. `        self._is_goal = None            # Is this tile the goal?`
120. `        self._print_path_info = False   # Print info from retrace path.`
121. ` `
122. `    def _is_goal_point(self, current_tile):`
123. `        '''Is this the goal point?`
124. ` `
125. `        current_tile -- List in [current + estimated distance, estimated`
126. `        distance, distance so far, (current x, current y), (parent x,`
127. `        parent y)] format.`
128. ` `
129. `        Return: Boolean. (True if the goal is found.)`
130. `        '''`
131. ` `
132. `        return current_tile[3] == (self._x2, self._y2)`
133. ` `
134. `    def _is_goal_tile(self, current_tile):`
135. `        '''Is this the goal tile?`
136. ` `
137. `        current_tile -- List in [current + estimated distance, estimated`
138. `        distance, distance so far, (current x, current y), (parent x,`
139. `        parent y)] format.`
140. ` `
141. ` `
142. `        Return: Boolean. (True if the goal is found.)`
143. `        '''`
144. ` `
145. `        cur_x1, cur_y1 = current_tile[3]`
146. ` `
147. `        return self.area.terrain[cur_y1][cur_x1] == self._tile`
148. ` `
149. `    def _is_goal_iterable(self, current_tile):`
150. `        '''Is this the goal as found in the iterable?`
151. ` `
152. `        current_tile -- List in [current + estimated distance, estimated`
153. `        distance, distance so far, (current x, current y), (parent x,`
154. `        parent y)] format.`
155. ` `
156. ` `
157. `        Return: Boolean. (True if the goal is found.)`
158. `        '''`
159. ` `
160. `        cur_x1, cur_y1 = current_tile[3]`
161. ` `
162. `        return self.area.terrain[cur_y1][cur_x1] in self._tiles`
163. ` `
164. `    def _cardinal_heuristic(self, x1, y1, x2, y2):`
165. `        '''Return the Manhattan distance.`
166. ` `
167. `        x1, y1, x2, y2 -- Integers. Start and end coordinates.`
168. ` `
169. `        Return: Integer or Float. (The distance estimate.)`
170. `        '''`
171. ` `
172. `        d_x, d_y = abs(x1 - x2), abs(y1 - y2)`
173. ` `
174. `        return (d_x + d_y) * self.c_dist`
175. ` `
176. `    def _diagonal_heuristic(self, x1, y1, x2, y2):`
177. `        '''Return a distance estimate for grids that allow diagonal movement.`
178. ` `
179. `        This is the 'octile heuristic' as defined on:`
180. `        https://github.com/riscy/a_star_on_grids#on-an-8-connected-grid`
181. ` `
182. `        x1, y1, x2, y2 -- Integers. Start and end coordinates.`
183. ` `
184. `        1: /r/rogulikedev's RIngan suggested:`
185. `        Chebyshev distance:`
186. `        max(d_x, d_y) * self.c_dist`
187. ` `
188. `        While simple, fast, and producing an admissible heuristic, the more`
189. `        diagonal the path the more an estimate would be low.`
190. ` `
191. `        2: /r/rogulikedev's chrisrayner suggested:`
192. `        https://github.com/riscy/a_star_on_grids#on-an-8-connected-grid`
193. ` `
194. `        C, D = self.c_dist, self.d_dist`
195. `        E = 2 * C - D`
196. `        (E * abs(d_x - d_y) + D * (d_x + d_y)) / 2`
197. ` `
198. `        or`
199. ` `
200. `        B = self.d_dist - self.c_dist`
201. `        C * d_x + B * d_y if d_x > d_y else`
202. `        C * d_y + B * d_x`
203. ` `
204. `        for a more accurate estimate. I settled on the latter.`
205. ` `
206. `        Return: Integer or Float. (The distance estimate.)`
207. `        '''`
208. ` `
209. `        d_x, d_y = abs(x1 - x2), abs(y1 - y2)`
210. ` `
211. `        # NOTE: Doing this with a max() and min() was slower on Python 3`
212. `        if d_x > d_y:`
213. `            return self.c_dist * d_x + (self.d_dist - self.c_dist) * d_y`
214. `        else:`
215. `            return self.c_dist * d_y + (self.d_dist - self.c_dist) * d_x`
216. ` `
217. `    def _purge_private(self):`
218. `        '''Purge Pathfinder()'s private values, usually before finding a new`
219. `        path.`
220. ` `
221. `        NOTE: self._heuristic = None preforms a Dijkstra search, set it to a`
222. `        heuristic to use an A-Star search.`
223. `        NOTE 2: self._closed_set_parent_map is a List of Lists initialized to`
224. `        None. Tiles in ._closed_set_coords put their parent coordinates at`
225. `        self._closed_set_parent_map[y][x] in (parent x, parent y) format.`
226. `        '''`
227. ` `
228. `        self._x2, self._y2 = None, None`
229. `        self._tile, self._tiles = None, None`
230. `        self._heuristic = None`
231. `        self._directions = None`
232. `        self._open_set_coords = set()`
233. `        self._open_set = []`
234. `        self._closed_set_coords = set()`
235. `        self._closed_set_parent_map = [self.__parent_map_row[:] for row in`
236. `                                       range(self.area.height)]`
237. `        self._is_goal = None`
238. `        self._unobstruct_goals = None`
239. ` `
240. `    def _look_for_open(self, current_tile, best_path):`
241. `        '''Add the eligible neighbours to open_set adjusting other tiles as`
242. `        needed.`
243. ` `
244. `        current_tile -- List in [current + estimated distance, estimated`
245. `        distance, distance so far, (current x, current y), (parent x,`
246. `        parent y)] format.`
247. `        best_path -- Boolean. 'True' to look for the best path. This is slower`
248. `        as it involves modifying already processed tiles and possibly breaking`
249. `        the heap invariant.`
250. `        '''`
251. ` `
252. `        x, y = current_tile[3]`
253. `        current_dist = current_tile[2]`
254. ` `
255. `        for direction in self._directions:`
256. `            # NOTE: Implementing a '1' based movement cost system should be`
257. `            # trivial in the following code.`
258. `            x_mod, y_mod, step_dist = direction`
259. `            new_x, new_y = x+x_mod, y+y_mod`
260. ` `
261. `            # If it's not in bounds...`
262. `            if 0 > new_x == self.area.width or 0 > new_y == self.area.height:`
263. ` `
264. `                continue`
265. `            else:`
266. `                the_tile = self.area.terrain[new_y][new_x]`
267. ` `
268. `            # Or if it is in the closed_set...`
269. `            if (new_x, new_y) in self._closed_set_coords:`
270. ` `
271. `                continue`
272. ` `
273. `            # If not unobstructing goals and it hits an obstruction...`
274. `            elif not self._unobstruct_goals and the_tile in\`
275. `                self.obstruction_characters:`
276. ` `
277. `                continue`
278. ` `
279. `            # When looking for a goal find it even if it's an obstruction when`
280. `            # unobstructing goals...`
281. `            elif self._unobstruct_goals and the_tile in\`
282. `                self.obstruction_characters:`
283. ` `
284. `                if self._x2 and self._y2 and (`
285. `                     new_x, new_y) != (self._x2, self._y2):`
286. ` `
287. `                    continue`
288. `                elif self._tile and self.area.terrain[`
289. `                     new_y][new_x] != self._tile:`
290. ` `
291. `                    continue`
292. `                elif self._tiles and self.area.terrain[`
293. `                     new_y][new_x] not in self._tiles:`
294. ` `
295. `                    continue`
296. ` `
297. `            # Update the distance travelled`
298. `            dist = current_dist + step_dist`
299. `            # Generate a heuristic distance for a goal that's a point.`
300. `            # NOTE: if self._heuristic == None then do a Dijkstra search`
301. `            # where the heuristic distance is just the distance traveled so`
302. `            # far, and the distance estimate is None.`
303. `            heuristic_estimate = None`
304. `            heuristic_distance = dist`
305. `            if self._heuristic:`
306. `                heuristic_estimate = self._heuristic(new_x, new_y,`
307. `                                                     self._x2, self._y2)`
308. `                heuristic_distance += heuristic_estimate`
309. ` `
310. `            # In the open_set and we want the best path.`
311. `            if best_path and (new_x, new_y) in self._open_set_coords:`
312. `                for tile in self._open_set:`
313. `                    if (new_x, new_y) == tile[3]:`
314. `                        # In the open_set and better.`
315. `                        if tile[2] > dist:`
316. `                            tile[0] = heuristic_distance`
317. `                            tile[1] = heuristic_estimate`
318. `                            tile[2] = dist`
319. `                            tile[4] = (x, y)`
320. `                            # Turns out naively re-heapifying is faster.`
321. `                            heapq.heapify(self._open_set)`
322. ` `
323. `                        break`
324. `            # Not in the open_set so add it.`
325. `            elif (new_x, new_y) not in self._open_set_coords:`
326. `                self._open_set_coords.add((new_x, new_y))`
327. `                heapq.heappush(self._open_set,`
328. `                               [heuristic_distance,     # Heuristic distance`
329. `                                heuristic_estimate,     # Estimated distance`
330. `                                dist,                   # Distance traveled`
331. `                                (new_x, new_y),         # (x, y)`
332. `                                (x, y)])                # (parent_x, parent_y)`
333. ` `
334. `    def _retrace_path(self, current_tile):`
335. `        '''Retrace a path to the start.`
336. ` `
337. `        current_tile -- List in [current + estimated distance, estimated`
338. `        distance, distance so far, (current x, current y), (parent x,`
339. `        parent y)] format.`
340. ` `
341. `        Retrace a path to (x1, y1). A path includes the (x, y) of the goal /`
342. `        target, but not that of the starting tile.`
343. ` `
344. `        NOTE: This will retrace the path of any tile back to the starting`
345. `        point, and may be useful for a number of purposes like building`
346. `        Dijkstra maps for multiple consumers.`
347. ` `
348. `        NOTE 2: Given python's recursion limit making this recursive is an iffy`
349. `        proposition.`
350. ` `
351. `        Return: deque(). (A deque of (x, y) Tuples representing the path.)`
352. `        '''`
353. ` `
354. `        parent = current_tile[4]`
355. `        the_path = deque()`
356. `        if parent:`
357. `            # Add the endpoint.`
358. `            the_path.appendleft(current_tile[3])`
359. ` `
360. `            while parent:`
361. `                # Add the parent until we get to to the starting x, y`
362. `                x, y = parent`
363. `                if self._closed_set_parent_map[y][x]:`
364. `                    the_path.appendleft(parent)`
365. `                parent = self._closed_set_parent_map[y][x]`
366. ` `
367. `        if self._print_path_info:`
368. `            print("\n\n==========")`
369. `            print("\nCurrent:")`
370. `            print(current_tile)`
371. `            # print("\nOpen Set Coordinates:")`
372. `            # print(self._open_set_coords)`
373. `            print("\nOpen Set Length:")`
374. `            print(len(self._open_set_coords))`
375. `            # print("\nClosed Set Coordinates:")`
376. `            # print(self._closed_set_coords)`
377. `            print("\nClosed Set Length:")`
378. `            print(len(self._closed_set_coords))`
379. `            print("\nPath:")`
380. `            print(the_path)`
381. `            print("\nTile Steps:")`
382. `            print(len(the_path))`
383. ` `
384. `        return the_path`
385. ` `
386. `    def _find_path(self, best_path, abort, goal_only):`
387. `        '''Find a path.`
388. ` `
389. `        best_path -- Boolean. 'True' to look for the best path. This is slower`
390. `        as it involves modifying already processed tiles and possibly breaking`
391. `        the heap invariant.`
392. `        abort -- False, or Integer. If the len(self._closed_set_coords) > abort`
393. `        stop searching. This should stop any 'too slow' away searches.`
394. `        goal_only -- Boolean. If True it will only return the (x, y, tile name)`
395. `        of the goal, and not the path. Faster than retracing the path.`
396. ` `
397. `        Return: deque, list, or None. (A deque of (x, y) Tuples, or a Tuple of`
398. `        (x, y, tile name) if goal only == true, or None if no path is found.)`
399. `        '''`
400. ` `
401. `        while self._open_set:`
402. `            current_tile = heapq.heappop(self._open_set)`
403. `            self._open_set_coords.remove(current_tile[3])`
404. `            x, y = current_tile[3]`
405. ` `
406. `            # Yay, we found the goal!`
407. `            if self._is_goal(current_tile) and not goal_only:`
408. `                return self._retrace_path(current_tile)`
409. `            elif self._is_goal(current_tile) and goal_only:`
410. `                return (x, y, self.area.terrain[y][x])`
411. ` `
412. `            # No goal, let's update the self._closed_set* and look for more`
413. `            # tiles...`
414. `            self._closed_set_coords.add(current_tile[3])`
415. `            # Abort search. Remember False == 0.`
416. `            if len(self._closed_set_coords) > abort > 0:`
417. `                return None`
418. `            self._closed_set_parent_map[y][x] = current_tile[4]`
419. `            self._look_for_open(current_tile, best_path)`
420. ` `
421. `        # Ooops, couldn't find a path!`
422. `        return None`
423. ` `
424. `    def find_point(self, x1, y1, x2, y2, use_diagonals=True, best_path=True,`
425. `                   abort=False):`
426. `        '''Look for a specified point.`
427. ` `
428. `        x1, y1, x2, y2 -- Integers. The start and end point.`
429. `        use_diagonals -- Boolean. Path including diagonal directions. This is`
430. `        slower as it has to check twice the tiles.`
431. `        best_path -- Boolean. 'True' to look for the best path. This is slower`
432. `        as it involves modifying already processed tiles and possibly breaking`
433. `        the heap invariant. If set to 'False' paths are often somewhat more`
434. `        organic, and can somewhat approximate a 'greedy best first' search.`
435. `        abort -- False, or Integer. If the 'len(self._closed_set_coords) >`
436. `        abort' stop searching. This should stop any 'too slow' searches.`
437. ` `
438. `        NOTE: This performs an A-Star search as it sets self._heuristic.`
439. ` `
440. `        Return: deque or None. (A deque of (x, y) Tuples, or None if no path`
441. `        is found.)`
442. `        '''`
443. ` `
444. `        self._purge_private()`
445. `        self._x2 = x2`
446. `        self._y2 = y2`
447. `        self._unobstruct_goals = False`
448. ` `
449. `        if use_diagonals:`
450. `            self._heuristic = self._diagonal_heuristic`
451. `            self._directions = set(self._cardinals + self._diagonals)`
452. `        else:`
453. `            self._heuristic = self._cardinal_heuristic`
454. `            self._directions = set(self._cardinals)`
455. ` `
456. `        self._is_goal = self._is_goal_point`
457. `        self._open_set_coords.add((x1, y1))`
458. `        heuristic_estimate = self._heuristic(x1, y1, x2, y2)`
459. ` `
460. `        heapq.heappush(self._open_set,`
461. `                       [0 + heuristic_estimate,         # A-Star`
462. `                        heuristic_estimate,             # Distance estimate`
463. `                        0,                              # Distance traveled`
464. `                        (x1, y1),                       # (x, y)`
465. `                        None])                          # (parent_x, parent_y)`
466. ` `
467. `        return self._find_path(best_path, abort, False)`
468. ` `
469. `    def is_point_findable(self, x1, y1, x2, y2, use_diagonals=True,`
470. `                          abort=False):`
471. `        '''Can the pathfider find a given point?`
472. ` `
473. `        NOTE: DO NOT USE THIS TO DETERMINE IF YOU SHOULD USE .find_point(), as`
474. `        you will be doing a search to do a search. In that case just use`
475. `        .find_point(). If you merely need to see if a tile is open please check`
476. `        the Area().terrain data structure. If you need LOS cast a ray, or use`
477. `        your FOV implementation. This is primarily useful for a 'blink' /`
478. `        'teleport' that requires a valid path, but may not be directly seen.`
479. ` `
480. `        x1, y1, x2, y2 -- Integers. The start and end point.`
481. `        use_diagonals -- Boolean. Path including diagonal directions. This is`
482. `        slower as it has to check twice the tiles.`
483. `        abort -- False, or Integer. If the 'len(self._closed_set_coords) >`
484. `        abort' stop searching. This should stop any 'too slow' searches.`
485. ` `
486. `        NOTE 2: This performs an A-Star search as it sets self._heuristic.`
487. ` `
488. `        Return: Boolean. (True if the point is findable)`
489. `        '''`
490. ` `
491. `        self._purge_private()`
492. `        self._x2 = x2`
493. `        self._y2 = y2`
494. `        self._unobstruct_goals = False`
495. ` `
496. `        if use_diagonals:`
497. `            self._heuristic = self._diagonal_heuristic`
498. `            self._directions = set(self._cardinals + self._diagonals)`
499. `        else:`
500. `            self._heuristic = self._cardinal_heuristic`
501. `            self._directions = set(self._cardinals)`
502. ` `
503. `        self._is_goal = self._is_goal_point`
504. `        self._open_set_coords.add((x1, y1))`
505. `        heuristic_estimate = self._heuristic(x1, y1, x2, y2)`
506. ` `
507. `        heapq.heappush(self._open_set,`
508. `                       [0 + heuristic_estimate,         # A-Star`
509. `                        heuristic_estimate,             # Distance estimate`
510. `                        0,                              # Distance traveled`
511. `                        (x1, y1),                       # (x, y)`
512. `                        None])                          # (parent_x, parent_y)`
513. ` `
514. `        found = self._find_path(False, abort, True)`
515. `        if found:`
516. `            return True`
517. `        else:`
518. `            return False`
519. ` `
520. `    def find_tile(self, x1, y1, tile, use_diagonals=True, best_path=True,`
521. `                  abort=False):`
522. `        '''Look for a specified tile, or tile in an iterable of tiles.`
523. ` `
524. `        x1, y1 -- Integers. The start point.`
525. `        tile -- String or Iterable. The tile, or an iterable of tiles, being`
526. `        sought.`
527. `        use_diagonals -- Boolean. Path including diagonal directions. This is`
528. `        slower as it has to check twice the tiles.`
529. `        best_path -- Boolean. 'True' to look for the best path. This is slower`
530. `        as it involves modifying already processed tiles and possibly breaking`
531. `        the heap invariant. If set to 'False' paths are often somewhat more`
532. `        organic, and can somewhat approximate a 'greedy best first' search.`
533. `        abort -- False, or Integer. If the 'len(self._closed_set_coords) >`
534. `        abort' stop searching. This should stop any 'too slow' searches.`
535. ` `
536. `        NOTE: This performs an Dijkstra search as it doesn't set`
537. `        self._heuristic.`
538. ` `
539. `        Return: deque or None. (A deque of (x, y) Tuples, or None if no path`
540. `        is found.)`
541. `        '''`
542. ` `
543. `        self._purge_private()`
544. ` `
545. `        if type(tile) == str:`
546. `            self._tile = tile`
547. `            self._is_goal = self._is_goal_tile`
548. `        else:`
549. `            self._tiles = tile`
550. `            self._is_goal = self._is_goal_iterable`
551. ` `
552. `        self._unobstruct_goals = True`
553. ` `
554. `        if use_diagonals:`
555. `            self._directions = set(self._cardinals + self._diagonals)`
556. `        else:`
557. `            self._directions = set(self._cardinals)`
558. ` `
559. `        self._open_set_coords.add((x1, y1))`
560. ` `
561. `        heapq.heappush(self._open_set,`
562. `                       [0,                              # Dijkstra`
563. `                        None,                           # Distance estimate`
564. `                        0,                              # Distance traveled`
565. `                        (x1, y1),                       # (x, y)`
566. `                        None])                          # (parent_x, parent_y)`
567. ` `
568. `        return self._find_path(best_path, abort, False)`
569. ` `
570. `    def nearest(self, x1, y1, tile, use_diagonals=True, abort=False):`
571. `        '''Look for a specified tile, or tile in an iterable of tiles, and`
572. `        return the location and name of that tile.`
573. ` `
574. `        x1, y1 -- Integers. The start point.`
575. `        tile -- String or Iterable. The tile, or an iterable of tiles, being`
576. `        sought.`
577. `        use_diagonals -- Boolean. Path including diagonal directions. This is`
578. `        slower as it has to check twice the tiles.`
579. `        abort -- False, or Integer. If the len(self._closed_set_coords) >`
580. `        abort stop searching. This should stop any 'too slow' away searches.`
581. ` `
582. `        NOTE: This performs an Dijkstra search as it doesn't set`
583. `        self._heuristic.`
584. ` `
585. `        Return: Tuple or None. (A Tuple of (x, y, tile name), or None.)`
586. `        '''`
587. ` `
588. `        self._purge_private()`
589. ` `
590. `        if type(tile) == str:`
591. `            self._tile = tile`
592. `            self._is_goal = self._is_goal_tile`
593. `        else:`
594. `            self._tiles = tile`
595. `            self._is_goal = self._is_goal_iterable`
596. ` `
597. `        self._unobstruct_goals = True`
598. ` `
599. `        if use_diagonals:`
600. `            self._directions = set(self._cardinals + self._diagonals)`
601. `        else:`
602. `            self._directions = set(self._cardinals)`
603. ` `
604. `        self._open_set_coords.add((x1, y1))`
605. ` `
606. `        heapq.heappush(self._open_set,`
607. `                       [0,                              # Dijkstra`
608. `                        None,                           # Distance estimate`
609. `                        0,                              # Distance traveled`
610. `                        (x1, y1),                       # (x, y)`
611. `                        None])                          # (parent_x, parent_y)`
612. ` `
613. `        return self._find_path(False, abort, True)`
614. ` `
615. ` `
616. `if __name__ == '__main__':`
617. `    '''Test the Pathfinder Class.'''`
618. ` `
619. `    dun = ["#########################################################&#######",`
620. `           "#.......#...#.........#...........#...............#.....#&#.-...#",`
621. `           "#######.~...#........#..........#...................#...#&#.#...#",`
622. `           "&&&&&&#.#...........#...........#~###################...###.#####",`
623. `           "#######.#...#####.##............#...................#.....§.....#",`
624. `           "#.......#...#&&#....##..........#...................#.....#####-#",`
625. `           "#####+###...####....##.......#####################..#.....#.....#",`
626. `           "#..##........................#&&#................#..#.....#.....#",`
627. `           "#...##...........#########...####.............#..#..#.....#.....#",`
628. `           "#....##..................#......#..###############..#.....#.....#",`
629. `           "#.....##.................#.#....#..#...#...#...#....#.....#.....#",`
630. `           "#......##.......#######..#.#....#....#...#...#...#..#.....#.##..#",`
631. `           "#...............#&&&&&#..#.#....#####################.....#.##..#",`
632. `           "#........#####..#&&&&&#..#.#.............#................##.#..#",`
633. `           "#........#&&&#..#######....#.............#................#.##..#",`
634. `           "#........#####.............#####.....#...#...#....###...####.#..#",`
635. `           "#..............##########.............#..#..#.....#&#...#&#.##..#",`
636. `           "#..............#........#..............#...#......###...####.#..#",`
637. `           "#.##...###..####........#..#####........#.#...............#..#..#",`
638. `           "#..............-........§..#........############..........####..#",`
639. `           "####.#.........#........#..#........#....#.....#.########.......#",`
640. `           "#.....#........##########..#.............#.......#&&#..###-####+#",`
641. `           "#.....##...................#.............#.......#####.#&#......#",`
642. `           "#.......#..................#.............#.......~.....#&#......#",`
643. `           "########################################################&########"]`
644. ` `
645. `    import pygame`
646. `    from pygame.locals import *`
647. `    import time`
648. `    from fnmatch import filter`
649. `    from sys import exit`
650. ` `
651. `    # Translate the character based map into Area().terrain tile names.`
652. `    # Tile names are used to avoid character clashes in more complex maps.`
653. `    rev = {}`
654. `    tmp_terrain = []`
655. ` `
656. `    for tile in config.TERRAIN_CHARACTERS:`
657. `        tmp = config.TERRAIN_CHARACTERS[tile]`
658. `        rev[tmp] = tile`
659. ` `
660. `    for y in range(len(dun)):`
661. `        tmp_terrain.append([])`
662. `        for x in range(len(dun[y])):`
663. `            tmp_terrain[y].append(rev[dun[y][x]])`
664. ` `
665. `    test_area = Area()`
666. `    test_area.terrain = tmp_terrain`
667. `    test_area.width = len(tmp_terrain[0])`
668. `    test_area.height = len(tmp_terrain)`
669. ` `
670. `    # An instance of the pathfinder.`
671. `    pathfinder = Pathfinder(test_area)`
672. ` `
673. `    # Initialize Pygame.`
674. `    pygame.display.init()`
675. `    pygame.font.init()`
676. ` `
677. `    clock = pygame.time.Clock()`
678. ` `
679. `    pygame.display.set_caption("Pathfinding Test")`
680. ` `
681. `    chosen_font = None`
682. `    installed_fonts = pygame.font.get_fonts()`
683. ` `
684. `    # Pick the first font from font_names, or the first font with *mono* in`
685. `    # the name.`
686. `    print("\nFONTS WITH MONO IN THE NAME:\n"`
687. `          "============================")`
688. `    print(filter(installed_fonts, "*mono*"))`
689. `    first_mono = filter(installed_fonts, "*mono*")[0]`
690. ` `
691. `    font_names = ["dejavusansmono",`
692. `                  "liberationmono",`
693. `                  "andalemono",`
694. `                  "lucidamono",`
695. `                  "notomono",`
696. `                  first_mono]`
697. ` `
698. `    chosen_font = pygame.font.match_font(`
699. `        [font_name for font_name in font_names if font_name in installed_fonts]`
700. `        [0])`
701. ` `
702. `    print("\nFONT:\n"`
703. `          "=====")`
704. `    print("Using font: " + chosen_font + '\n')`
705. ` `
706. `    font_size = 20`
707. `    font = pygame.font.Font(chosen_font, font_size)`
708. `    font_w, font_h = font.size(" ")`
709. ` `
710. `    font_size2 = 14`
711. `    font2 = pygame.font.Font(chosen_font, font_size2)`
712. ` `
713. `    # The goal and player x and y.`
714. `    gx, gy = 8, 8`
715. `    px, py = 10, 10`
716. ` `
717. `    default_fps = 60`
718. ` `
719. `    R_color = 'red'`
720. `    G_color = 'lime'`
721. `    B_color = 'blue'`
722. `    F_color = 'fuchsia'`
723. ` `
724. `    pygame.key.set_repeat(250, 1000 // default_fps)`
725. ` `
726. `    win = pygame.display.set_mode((test_area.width * font_w,`
727. `                                   (test_area.height + 1) * font_h))`
728. ` `
729. `    win.fill(config.COLORNAMES['black'])`
730. `    txt1 = font.render("WSAD to move '?', and ???? to move '@'.", True,`
731. `                       config.COLORNAMES['white'])`
732. `    txt2 = font.render("Press an any key to begin...", True,`
733. `                       config.COLORNAMES['white'])`
734. `    win.blit(txt1, (0, font_h * 5))`
735. `    win.blit(txt2, (0, font_h * 7))`
736. ` `
737. `    pygame.display.flip()`
738. ` `
739. `    pad_h = test_area.height - 3`
740. `    pad_w = test_area.width - 3`
741. ` `
742. `    wait = True`
743. `    while wait:`
744. `        for event in pygame.event.get():`
745. `            clock.tick(default_fps)`
746. `            if event.type == KEYDOWN:`
747. `                    wait = False`
748. ` `
749. `    win.fill(config.COLORNAMES['black'])`
750. ` `
751. `    # The main loop.`
752. `    while True:`
753. `        # Set the FPS`
754. `        clock.tick(default_fps)`
755. ` `
756. `        for event in pygame.event.get():`
757. `            if (event.type == QUIT or event.type == KEYDOWN and`
758. `                    event.key == K_ESCAPE):`
759. `                pygame.quit()`
760. `                exit()`
761. ` `
762. `            if event.type == KEYDOWN:`
763. `                if event.key == K_UP:`
764. `                    if py > 1:`
765. `                        py -= 1`
766. `                elif event.key == K_DOWN:`
767. `                    if py <= pad_h:`
768. `                        py += 1`
769. `                elif event.key == K_LEFT:`
770. `                    if px > 1:`
771. `                        px -= 1`
772. `                elif event.key == K_RIGHT:`
773. `                    if px <= pad_w:`
774. `                        px += 1`
775. `                elif event.unicode == 'w':`
776. `                    if gy > 1:`
777. `                        gy -= 1`
778. `                elif event.unicode == 's':`
779. `                    if gy <= pad_h:`
780. `                        gy += 1`
781. `                elif event.unicode == 'a':`
782. `                    if gx > 1:`
783. `                        gx -= 1`
784. `                elif event.unicode == 'd':`
785. `                    if gx <= pad_w:`
786. `                        gx += 1`
787. ` `
788. `                # Calculate and (crudely) time the paths.`
789. `                t1 = time.time()`
790. `                # Find the Goal '?'`
791. `                r1 = pathfinder.is_point_findable(px, py, gx, gy,`
792. `                                                  use_diagonals=True,`
793. `                                                  abort=False)`
794. `                t2 = time.time()`
795. `                # Red Path`
796. `                r2 = pathfinder.find_point(px, py, gx, gy,`
797. `                                           best_path=True,`
798. `                                           use_diagonals=True,`
799. `                                           abort=False)`
800. `                t3 = time.time()`
801. `                # Green Path`
802. `                r3 = pathfinder.find_tile(px, py, 'open door',`
803. `                                          best_path=True,`
804. `                                          use_diagonals=True,`
805. `                                          abort=False)`
806. `                t4 = time.time()`
807. `                # Blue Path`
808. `                r4 = pathfinder.find_tile(px, py, ['closed door',`
809. `                                                   'closed secret door'],`
810. `                                          best_path=True,`
811. `                                          use_diagonals=True,`
812. `                                          abort=False)`
813. `                t5 = time.time()`
814. `                # Fuchsia Path`
815. `                r5 = pathfinder.nearest(px, py, 'open secret door',`
816. `                                        use_diagonals=True,`
817. `                                        abort=False)`
818. `                t6 = time.time()`
819. ` `
820. `                win.fill(config.COLORNAMES['black'])`
821. ` `
822. `                # Display the area on the given window.`
823. `                for x1 in range(test_area.width):`
824. `                    for y1 in range(test_area.height):`
825. ` `
826. `                        char = None`
827. ` `
828. `                        if r2 and (x1, y1) in r2:`
829. `                            color = R_color`
830. `                        elif r3 and (x1, y1) in r3:`
831. `                            color = G_color`
832. `                        elif r4 and (x1, y1) in r4:`
833. `                            color = B_color`
834. `                        elif r5 and (x1, y1) ==\`
835. `                            (r5[0], r5[1]):`
836. `                            color = F_color`
837. `                        else:`
838. `                            color = config.TERRAIN_COLORS[`
839. `                                        test_area.terrain[y1][x1]]`
840. ` `
841. `                        char = config.TERRAIN_CHARACTERS[`
842. `                            test_area.terrain[y1][x1]]`
843. ` `
844. `                        if x1 == px and y1 == py:`
845. `                            color = 'yellow'`
846. `                            char = '@'`
847. ` `
848. `                        elif x1 == gx and y1 == gy:`
849. `                            color = 'teal'`
850. `                            char = '?'`
851. ` `
852. `                        if char:`
853. `                            char_surf = font.render(char, True,`
854. `                                                    config.COLORNAMES[color])`
855. `                            win.blit(char_surf, (x1 * font_w, y1 * font_h))`
856. ` `
857. `                goal_found = 'False'`
858. `                if r1:`
859. `                    goal_found = str(round(t2 - t1, 4))`
860. ` `
861. `                txt = ('|R Path in: ' +`
862. `                       str(round(t3 - t2, 4)) +`
863. `                       ' |G Path in: ' +`
864. `                       str(round(t4 - t3, 4)) +`
865. `                       ' |B Path in: ' +`
866. `                       str(round(t5 - t4, 4)) +`
867. `                       ' |F Path in: ' +`
868. `                       str(round(t6 - t5, 4)) +`
869. `                       ' |? Found in: ' +`
870. `                       goal_found + ' |')`
871. ` `
872. `                txt3 = font2.render(txt, True, config.COLORNAMES['white'])`
873. `                win.blit(txt3, (0, font_h * test_area.height))`
874. ` `
875. `                pygame.display.flip()`

Even if your language of choice isn't Python, I hope you find this pathfinder helpful to your endeavours. Cheers!