A Python 3 and 2 Pathfinder with Pygame Example

From RogueBasin
Jump to: navigation, search

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. Additionally, it is licensed under CC0, so use it for whatever you want.

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:

Pathfinding Test.png


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 makes it easy to download the code, and has rather better code highlighting.

http://pastebin.com/jHeKc6j0


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.             # Not in the open_set so add it.
  311.             if (new_x, new_y) not in self._open_set_coords:
  312.                 self._open_set_coords.add((new_x, new_y))
  313.                 heapq.heappush(self._open_set,
  314.                                [heuristic_distance,     # Heuristic distance
  315.                                 heuristic_estimate,     # Estimated distance
  316.                                 dist,                   # Distance traveled
  317.                                 (new_x, new_y),         # (x, y)
  318.                                 (x, y)])                # (parent_x, parent_y)
  319.  
  320.                 continue
  321.             # In the open_set and we want the best path.
  322.             elif best_path and (new_x, new_y) in self._open_set_coords:
  323.                 for tile in self._open_set:
  324.                     if (new_x, new_y) == tile[3]:
  325.                         # In the open_set and better.
  326.                         if tile[2] > dist:
  327.                             tile[0] = heuristic_distance
  328.                             tile[1] = heuristic_estimate
  329.                             tile[2] = dist
  330.                             tile[4] = (x, y)
  331.                             # Turns out naively re-heapifying is faster.
  332.                             heapq.heapify(self._open_set)
  333.  
  334.                         break
  335.  
  336.     def _retrace_path(self, current_tile):
  337.         '''Retrace a path to the start.
  338.  
  339.         current_tile -- List in [current + estimated distance, estimated
  340.         distance, distance so far, (current x, current y), (parent x,
  341.         parent y)] format.
  342.  
  343.         Retrace a path to (x1, y1). A path includes the (x, y) of the goal /
  344.         target, but not that of the starting tile.
  345.  
  346.         NOTE: This will retrace the path of any tile back to the starting
  347.         point, and may be useful for a number of purposes like building
  348.         Dijkstra maps for multiple consumers.
  349.  
  350.         NOTE 2: Given python's recursion limit making this recursive is an iffy
  351.         proposition.
  352.  
  353.         Return: deque(). (A deque of (x, y) Tuples representing the path.)
  354.         '''
  355.  
  356.         parent = current_tile[4]
  357.         the_path = deque()
  358.         if parent:
  359.             # Add the endpoint.
  360.             the_path.appendleft(current_tile[3])
  361.  
  362.             while parent:
  363.                 # Add the parent until we get to to the starting x, y
  364.                 x, y = parent
  365.                 if self._closed_set_parent_map[y][x]:
  366.                     the_path.appendleft(parent)
  367.                 parent = self._closed_set_parent_map[y][x]
  368.  
  369.         if self._print_path_info:
  370.             print("\n\n==========")
  371.             print("\nCurrent:")
  372.             print(current_tile)
  373.             # print("\nOpen Set Coordinates:")
  374.             # print(self._open_set_coords)
  375.             print("\nOpen Set Length:")
  376.             print(len(self._open_set_coords))
  377.             # print("\nClosed Set Coordinates:")
  378.             # print(self._closed_set_coords)
  379.             print("\nClosed Set Length:")
  380.             print(len(self._closed_set_coords))
  381.             print("\nPath:")
  382.             print(the_path)
  383.             print("\nTile Steps:")
  384.             print(len(the_path))
  385.  
  386.         return the_path
  387.  
  388.     def _find_path(self, best_path, abort, goal_only):
  389.         '''Find a path.
  390.  
  391.         best_path -- Boolean. 'True' to look for the best path. This is slower
  392.         as it involves modifying already processed tiles and possibly breaking
  393.         the heap invariant.
  394.         abort -- False, or Integer. If the len(self._closed_set_coords) > abort
  395.         stop searching. This should stop any 'too slow' away searches.
  396.         goal_only -- Boolean. If True it will only return the (x, y, tile name)
  397.         of the goal, and not the path. Faster than retracing the path.
  398.  
  399.         Return: deque, list, or None. (A deque of (x, y) Tuples, or a Tuple of
  400.         (x, y, tile name) if goal only == true, or None if no path is found.)
  401.         '''
  402.  
  403.         while self._open_set:
  404.             current_tile = heapq.heappop(self._open_set)
  405.             self._open_set_coords.remove(current_tile[3])
  406.             x, y = current_tile[3]
  407.  
  408.             # Yay, we found the goal!
  409.             if self._is_goal(current_tile) and not goal_only:
  410.                 return self._retrace_path(current_tile)
  411.             elif self._is_goal(current_tile) and goal_only:
  412.                 return (x, y, self.area.terrain[y][x])
  413.  
  414.             # No goal, let's update the self._closed_set* and look for more
  415.             # tiles...
  416.             self._closed_set_coords.add(current_tile[3])
  417.             # Abort search. Remember False == 0.
  418.             if len(self._closed_set_coords) > abort > 0:
  419.                 return None
  420.             self._closed_set_parent_map[y][x] = current_tile[4]
  421.             self._look_for_open(current_tile, best_path)
  422.  
  423.         # Ooops, couldn't find a path!
  424.         return None
  425.  
  426.     def find_point(self, x1, y1, x2, y2, use_diagonals=True, best_path=True,
  427.                    abort=False):
  428.         '''Look for a specified point.
  429.  
  430.         x1, y1, x2, y2 -- Integers. The start and end point.
  431.         use_diagonals -- Boolean. Path including diagonal directions. This is
  432.         slower as it has to check twice the tiles.
  433.         best_path -- Boolean. 'True' to look for the best path. This is slower
  434.         as it involves modifying already processed tiles and possibly breaking
  435.         the heap invariant. If set to 'False' paths are often somewhat more
  436.         organic, and can somewhat approximate a 'greedy best first' search.
  437.         abort -- False, or Integer. If the 'len(self._closed_set_coords) >
  438.         abort' stop searching. This should stop any 'too slow' searches.
  439.  
  440.         NOTE: This performs an A-Star search as it sets self._heuristic.
  441.  
  442.         Return: deque or None. (A deque of (x, y) Tuples, or None if no path
  443.         is found.)
  444.         '''
  445.  
  446.         self._purge_private()
  447.         self._x2 = x2
  448.         self._y2 = y2
  449.         self._unobstruct_goals = False
  450.  
  451.         if use_diagonals:
  452.             self._heuristic = self._diagonal_heuristic
  453.             self._directions = set(self._cardinals + self._diagonals)
  454.         else:
  455.             self._heuristic = self._cardinal_heuristic
  456.             self._directions = set(self._cardinals)
  457.  
  458.         self._is_goal = self._is_goal_point
  459.         self._open_set_coords.add((x1, y1))
  460.         heuristic_estimate = self._heuristic(x1, y1, x2, y2)
  461.  
  462.         heapq.heappush(self._open_set,
  463.                        [0 + heuristic_estimate,         # A-Star
  464.                         heuristic_estimate,             # Distance estimate
  465.                         0,                              # Distance traveled
  466.                         (x1, y1),                       # (x, y)
  467.                         None])                          # (parent_x, parent_y)
  468.  
  469.         return self._find_path(best_path, abort, False)
  470.  
  471.     def is_point_findable(self, x1, y1, x2, y2, use_diagonals=True,
  472.                           abort=False):
  473.         '''Can the pathfider find a given point?
  474.  
  475.         NOTE: DO NOT USE THIS TO DETERMINE IF YOU SHOULD USE .find_point(), as
  476.         you will be doing a search to do a search. In that case just use
  477.         .find_point(). If you merely need to see if a tile is open please check
  478.         the Area().terrain data structure. If you need LOS cast a ray, or use
  479.         your FOV implementation. This is primarily useful for a 'blink' /
  480.         'teleport' that requires a valid path, but may not be directly seen.
  481.  
  482.         x1, y1, x2, y2 -- Integers. The start and end point.
  483.         use_diagonals -- Boolean. Path including diagonal directions. This is
  484.         slower as it has to check twice the tiles.
  485.         abort -- False, or Integer. If the 'len(self._closed_set_coords) >
  486.         abort' stop searching. This should stop any 'too slow' searches.
  487.  
  488.         NOTE 2: This performs an A-Star search as it sets self._heuristic.
  489.  
  490.         Return: Boolean. (True if the point is findable)
  491.         '''
  492.  
  493.         self._purge_private()
  494.         self._x2 = x2
  495.         self._y2 = y2
  496.         self._unobstruct_goals = False
  497.  
  498.         if use_diagonals:
  499.             self._heuristic = self._diagonal_heuristic
  500.             self._directions = set(self._cardinals + self._diagonals)
  501.         else:
  502.             self._heuristic = self._cardinal_heuristic
  503.             self._directions = set(self._cardinals)
  504.  
  505.         self._is_goal = self._is_goal_point
  506.         self._open_set_coords.add((x1, y1))
  507.         heuristic_estimate = self._heuristic(x1, y1, x2, y2)
  508.  
  509.         heapq.heappush(self._open_set,
  510.                        [0 + heuristic_estimate,         # A-Star
  511.                         heuristic_estimate,             # Distance estimate
  512.                         0,                              # Distance traveled
  513.                         (x1, y1),                       # (x, y)
  514.                         None])                          # (parent_x, parent_y)
  515.  
  516.         found = self._find_path(False, abort, True)
  517.         if found:
  518.             return True
  519.         else:
  520.             return False
  521.  
  522.     def find_tile(self, x1, y1, tile, use_diagonals=True, best_path=True,
  523.                   abort=False):
  524.         '''Look for a specified tile, or tile in an iterable of tiles.
  525.  
  526.         x1, y1 -- Integers. The start point.
  527.         tile -- String or Iterable. The tile, or an iterable of tiles, being
  528.         sought.
  529.         use_diagonals -- Boolean. Path including diagonal directions. This is
  530.         slower as it has to check twice the tiles.
  531.         best_path -- Boolean. 'True' to look for the best path. This is slower
  532.         as it involves modifying already processed tiles and possibly breaking
  533.         the heap invariant. If set to 'False' paths are often somewhat more
  534.         organic, and can somewhat approximate a 'greedy best first' search.
  535.         abort -- False, or Integer. If the 'len(self._closed_set_coords) >
  536.         abort' stop searching. This should stop any 'too slow' searches.
  537.  
  538.         NOTE: This performs an Dijkstra search as it doesn't set
  539.         self._heuristic.
  540.  
  541.         Return: deque or None. (A deque of (x, y) Tuples, or None if no path
  542.         is found.)
  543.         '''
  544.  
  545.         self._purge_private()
  546.  
  547.         if type(tile) == str:
  548.             self._tile = tile
  549.             self._is_goal = self._is_goal_tile
  550.         else:
  551.             self._tiles = tile
  552.             self._is_goal = self._is_goal_iterable
  553.  
  554.         self._unobstruct_goals = True
  555.  
  556.         if use_diagonals:
  557.             self._directions = set(self._cardinals + self._diagonals)
  558.         else:
  559.             self._directions = set(self._cardinals)
  560.  
  561.         self._open_set_coords.add((x1, y1))
  562.  
  563.         heapq.heappush(self._open_set,
  564.                        [0,                              # Dijkstra
  565.                         None,                           # Distance estimate
  566.                         0,                              # Distance traveled
  567.                         (x1, y1),                       # (x, y)
  568.                         None])                          # (parent_x, parent_y)
  569.  
  570.         return self._find_path(best_path, abort, False)
  571.  
  572.     def nearest(self, x1, y1, tile, use_diagonals=True, abort=False):
  573.         '''Look for a specified tile, or tile in an iterable of tiles, and
  574.         return the location and name of that tile.
  575.  
  576.         x1, y1 -- Integers. The start point.
  577.         tile -- String or Iterable. The tile, or an iterable of tiles, being
  578.         sought.
  579.         use_diagonals -- Boolean. Path including diagonal directions. This is
  580.         slower as it has to check twice the tiles.
  581.         abort -- False, or Integer. If the len(self._closed_set_coords) >
  582.         abort stop searching. This should stop any 'too slow' away searches.
  583.  
  584.         NOTE: This performs an Dijkstra search as it doesn't set
  585.         self._heuristic.
  586.  
  587.         Return: Tuple or None. (A Tuple of (x, y, tile name), or None.)
  588.         '''
  589.  
  590.         self._purge_private()
  591.  
  592.         if type(tile) == str:
  593.             self._tile = tile
  594.             self._is_goal = self._is_goal_tile
  595.         else:
  596.             self._tiles = tile
  597.             self._is_goal = self._is_goal_iterable
  598.  
  599.         self._unobstruct_goals = True
  600.  
  601.         if use_diagonals:
  602.             self._directions = set(self._cardinals + self._diagonals)
  603.         else:
  604.             self._directions = set(self._cardinals)
  605.  
  606.         self._open_set_coords.add((x1, y1))
  607.  
  608.         heapq.heappush(self._open_set,
  609.                        [0,                              # Dijkstra
  610.                         None,                           # Distance estimate
  611.                         0,                              # Distance traveled
  612.                         (x1, y1),                       # (x, y)
  613.                         None])                          # (parent_x, parent_y)
  614.  
  615.         return self._find_path(False, abort, True)
  616.  
  617.  
  618. if __name__ == '__main__':
  619.     '''Test the Pathfinder Class.'''
  620.  
  621.     dun = ["#########################################################&#######",
  622.            "#.......#...#.........#...........#...............#.....#&#.-...#",
  623.            "#######.~...#........#..........#...................#...#&#.#...#",
  624.            "&&&&&&#.#...........#...........#~###################...###.#####",
  625.            "#######.#...#####.##............#...................#.....§.....#",
  626.            "#.......#...#&&#....##..........#...................#.....#####-#",
  627.            "#####+###...####....##.......#####################..#.....#.....#",
  628.            "#..##........................#&&#................#..#.....#.....#",
  629.            "#...##...........#########...####.............#..#..#.....#.....#",
  630.            "#....##..................#......#..###############..#.....#.....#",
  631.            "#.....##.................#.#....#..#...#...#...#....#.....#.....#",
  632.            "#......##.......#######..#.#....#....#...#...#...#..#.....#.##..#",
  633.            "#...............#&&&&&#..#.#....#####################.....#.##..#",
  634.            "#........#####..#&&&&&#..#.#.............#................##.#..#",
  635.            "#........#&&&#..#######....#.............#................#.##..#",
  636.            "#........#####.............#####.....#...#...#....###...####.#..#",
  637.            "#..............##########.............#..#..#.....#&#...#&#.##..#",
  638.            "#..............#........#..............#...#......###...####.#..#",
  639.            "#.##...###..####........#..#####........#.#...............#..#..#",
  640.            "#..............-........§..#........############..........####..#",
  641.            "####.#.........#........#..#........#....#.....#.########.......#",
  642.            "#.....#........##########..#.............#.......#&&#..###-####+#",
  643.            "#.....##...................#.............#.......#####.#&#......#",
  644.            "#.......#..................#.............#.......~.....#&#......#",
  645.            "########################################################&########"]
  646.  
  647.     import pygame
  648.     from pygame.locals import *
  649.     import time
  650.     from fnmatch import filter
  651.     from sys import exit
  652.  
  653.     # Translate the character based map into Area().terrain tile names.
  654.     # Tile names are used to avoid character clashes in more complex maps.
  655.     rev = {}
  656.     tmp_terrain = []
  657.  
  658.     for tile in config.TERRAIN_CHARACTERS:
  659.         tmp = config.TERRAIN_CHARACTERS[tile]
  660.         rev[tmp] = tile
  661.  
  662.     for y in range(len(dun)):
  663.         tmp_terrain.append([])
  664.         for x in range(len(dun[y])):
  665.             tmp_terrain[y].append(rev[dun[y][x]])
  666.  
  667.     test_area = Area()
  668.     test_area.terrain = tmp_terrain
  669.     test_area.width = len(tmp_terrain[0])
  670.     test_area.height = len(tmp_terrain)
  671.  
  672.     # An instance of the pathfinder.
  673.     pathfinder = Pathfinder(test_area)
  674.  
  675.     # Initialize Pygame.
  676.     pygame.display.init()
  677.     pygame.font.init()
  678.  
  679.     clock = pygame.time.Clock()
  680.  
  681.     pygame.display.set_caption("Pathfinding Test")
  682.  
  683.     chosen_font = None
  684.     installed_fonts = pygame.font.get_fonts()
  685.  
  686.     # Pick the first font from font_names, or the first font with *mono* in
  687.     # the name.
  688.     print("\nFONTS WITH MONO IN THE NAME:\n"
  689.           "============================")
  690.     print(filter(installed_fonts, "*mono*"))
  691.     first_mono = filter(installed_fonts, "*mono*")[0]
  692.  
  693.     font_names = ["dejavusansmono",
  694.                   "liberationmono",
  695.                   "andalemono",
  696.                   "lucidamono",
  697.                   "notomono",
  698.                   first_mono]
  699.  
  700.     chosen_font = pygame.font.match_font(
  701.         [font_name for font_name in font_names if font_name in installed_fonts]
  702.         [0])
  703.  
  704.     print("\nFONT:\n"
  705.           "=====")
  706.     print("Using font: " + chosen_font + '\n')
  707.  
  708.     font_size = 20
  709.     font = pygame.font.Font(chosen_font, font_size)
  710.     font_w, font_h = font.size(" ")
  711.  
  712.     font_size2 = 14
  713.     font2 = pygame.font.Font(chosen_font, font_size2)
  714.  
  715.     # The goal and player x and y.
  716.     gx, gy = 8, 8
  717.     px, py = 10, 10
  718.  
  719.     default_fps = 60
  720.  
  721.     R_color = 'red'
  722.     G_color = 'lime'
  723.     B_color = 'blue'
  724.     F_color = 'fuchsia'
  725.  
  726.     pygame.key.set_repeat(250, 1000 // default_fps)
  727.  
  728.     win = pygame.display.set_mode((test_area.width * font_w,
  729.                                    (test_area.height + 1) * font_h))
  730.  
  731.     win.fill(config.COLORNAMES['black'])
  732.     txt1 = font.render("WSAD to move '$', and UP, DOWN, LEFT, " +
  733.                        "RIGHT, to move '@'.", True,
  734.                        config.COLORNAMES['white'])
  735.     txt2 = font.render("Press an any key to begin...", True,
  736.                        config.COLORNAMES['white'])
  737.     win.blit(txt1, (0, font_h * 5))
  738.     win.blit(txt2, (0, font_h * 7))
  739.  
  740.     pygame.display.flip()
  741.  
  742.     pad_h = test_area.height - 3
  743.     pad_w = test_area.width - 3
  744.  
  745.     wait = True
  746.     while wait:
  747.         for event in pygame.event.get():
  748.             clock.tick(default_fps)
  749.             if event.type == KEYDOWN:
  750.                     wait = False
  751.  
  752.     win.fill(config.COLORNAMES['black'])
  753.  
  754.     # The main loop.
  755.     while True:
  756.         # Set the FPS
  757.         clock.tick(default_fps)
  758.  
  759.         for event in pygame.event.get():
  760.             if (event.type == QUIT or event.type == KEYDOWN and
  761.                     event.key == K_ESCAPE):
  762.                 pygame.quit()
  763.                 exit()
  764.  
  765.             if event.type == KEYDOWN:
  766.                 if event.key == K_UP:
  767.                     if py > 1:
  768.                         py -= 1
  769.                 elif event.key == K_DOWN:
  770.                     if py <= pad_h:
  771.                         py += 1
  772.                 elif event.key == K_LEFT:
  773.                     if px > 1:
  774.                         px -= 1
  775.                 elif event.key == K_RIGHT:
  776.                     if px <= pad_w:
  777.                         px += 1
  778.                 elif event.unicode == 'w':
  779.                     if gy > 1:
  780.                         gy -= 1
  781.                 elif event.unicode == 's':
  782.                     if gy <= pad_h:
  783.                         gy += 1
  784.                 elif event.unicode == 'a':
  785.                     if gx > 1:
  786.                         gx -= 1
  787.                 elif event.unicode == 'd':
  788.                     if gx <= pad_w:
  789.                         gx += 1
  790.  
  791.                 # Calculate and (crudely) time the paths.
  792.                 t1 = time.time()
  793.                 # Find the Goal '$'
  794.                 r1 = pathfinder.is_point_findable(px, py, gx, gy,
  795.                                                   use_diagonals=True,
  796.                                                   abort=False)
  797.                 t2 = time.time()
  798.                 # Red Path
  799.                 r2 = pathfinder.find_point(px, py, gx, gy,
  800.                                            best_path=True,
  801.                                            use_diagonals=True,
  802.                                            abort=False)
  803.                 t3 = time.time()
  804.                 # Green Path
  805.                 r3 = pathfinder.find_tile(px, py, 'open door',
  806.                                           best_path=True,
  807.                                           use_diagonals=True,
  808.                                           abort=False)
  809.                 t4 = time.time()
  810.                 # Blue Path
  811.                 r4 = pathfinder.find_tile(px, py, ['closed door',
  812.                                                    'closed secret door'],
  813.                                           best_path=True,
  814.                                           use_diagonals=True,
  815.                                           abort=False)
  816.                 t5 = time.time()
  817.                 # Fuchsia Path
  818.                 r5 = pathfinder.nearest(px, py, 'open secret door',
  819.                                         use_diagonals=True,
  820.                                         abort=False)
  821.                 t6 = time.time()
  822.  
  823.                 win.fill(config.COLORNAMES['black'])
  824.  
  825.                 # Display the area on the given window.
  826.                 for x1 in range(test_area.width):
  827.                     for y1 in range(test_area.height):
  828.  
  829.                         char = None
  830.  
  831.                         if r2 and (x1, y1) in r2:
  832.                             color = R_color
  833.                         elif r3 and (x1, y1) in r3:
  834.                             color = G_color
  835.                         elif r4 and (x1, y1) in r4:
  836.                             color = B_color
  837.                         elif r5 and (x1, y1) ==\
  838.                             (r5[0], r5[1]):
  839.                             color = F_color
  840.                         else:
  841.                             color = config.TERRAIN_COLORS[
  842.                                         test_area.terrain[y1][x1]]
  843.  
  844.                         char = config.TERRAIN_CHARACTERS[
  845.                             test_area.terrain[y1][x1]]
  846.  
  847.                         if x1 == px and y1 == py:
  848.                             color = 'yellow'
  849.                             char = '@'
  850.  
  851.                         elif x1 == gx and y1 == gy:
  852.                             color = 'teal'
  853.                             char = '$'
  854.  
  855.                         if char:
  856.                             char_surf = font.render(char, True,
  857.                                                     config.COLORNAMES[color])
  858.                             win.blit(char_surf, (x1 * font_w, y1 * font_h))
  859.  
  860.                 goal_found = 'False'
  861.                 if r1:
  862.                     goal_found = str(round(t2 - t1, 4))
  863.  
  864.                 txt = ('|R Path in: ' +
  865.                        str(round(t3 - t2, 4)) +
  866.                        ' |G Path in: ' +
  867.                        str(round(t4 - t3, 4)) +
  868.                        ' |B Path in: ' +
  869.                        str(round(t5 - t4, 4)) +
  870.                        ' |F Path in: ' +
  871.                        str(round(t6 - t5, 4)) +
  872.                        ' |$ Found in: ' +
  873.                        goal_found + ' |')
  874.  
  875.                 txt3 = font2.render(txt, True, config.COLORNAMES['white'])
  876.                 win.blit(txt3, (0, font_h * test_area.height))
  877.  
  878.                 pygame.display.flip()

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

Personal tools