Advertisement
Guest User

Untitled

a guest
Apr 15th, 2013
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.29 KB | None | 0 0
  1. import numpy
  2.  
  3.  
  4. ## Generate a "heat map" that represents how far away each cell in the provided
  5. # map is from any of the goal cells. The heat map can be used to allow entities
  6. # to move towards those goal cells by simply examining their neighbors and
  7. # moving to the one with the shortest remaining distance.
  8. # \param gridMap A Numpy array where 0 represents "open" and any
  9. #         other value represents "closed"
  10. # \param goals A list (set, etc.) of (x, y) tuples representing the goal
  11. #        tiles.
  12. def getHeatMap(gridMap, goals):
  13.     # A Numpy array of integers where each value is
  14.     # the distance the corresponding cell in gridMap is from any goal tile.
  15.     # Start with all non-goal tiles at -1 and all goal tiles at 0.
  16.     heatMap = numpy.ones(gridMap.shape, dtype = numpy.int32) * -1
  17.     for x, y in goals:
  18.         heatMap[(x, y)] = 0
  19.  
  20.     xVals, yVals = numpy.where(gridMap != 0)
  21.     # Maps cells we've seen to their costs. Add unreachable cells here so we
  22.     # never try to reach them.
  23.     cellToCost = dict([((xVals[i], yVals[i]), -1) for i in xrange(len(xVals))])
  24.     # Queue of cells waiting to be scanned.
  25.     cellQueue = []
  26.     # Max values to feed into xrange when getting neighbors.
  27.     maxX = gridMap.shape[0]
  28.     maxY = gridMap.shape[1]
  29.     for x, y in goals:
  30.         cellToCost[(x, y)] = 0
  31.         for xi in xrange(max(0, x - 1), min(maxX, x + 2)):
  32.             for yi in xrange(max(0, y - 1), min(maxY, y + 2)):
  33.                 if (xi, yi) not in cellToCost and gridMap[xi, yi] == 0:
  34.                     cellToCost[(xi, yi)] = 1
  35.                     heatMap[(xi, yi)] = 1
  36.                     cellQueue.append((xi, yi))
  37.  
  38.     # Pop a cell, examine its neighbors, and add any not-yet-processed
  39.     # neighbors to the queue. This is a simple breadth-first search.
  40.     while cellQueue:
  41.         pos = cellQueue.pop(0)
  42.         cost = cellToCost[pos]
  43.         # Find all neighbors for whom we have a new route.
  44.         for xi in xrange(max(0, pos[0] - 1), min(maxX, pos[0] + 2)):
  45.             for yi in xrange(max(0, pos[1] - 1), min(maxY, pos[1] + 2)):
  46.                 if (xi, yi) not in cellToCost:
  47.                     cellToCost[(xi, yi)] = cost + 1
  48.                     heatMap[(xi, yi)] = cost + 1
  49.                     cellQueue.append((xi, yi))
  50.     return heatMap
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement