Created
January 26, 2012 21:12
-
-
Save homelinen/1685129 to your computer and use it in GitHub Desktop.
Method For finding the chase path for an enemy in a maze game
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Use A* algorithm to find the best path to the playerPos | |
* in the maze: theMaze. | |
* @param playerPos | |
* @param theMaze | |
*/ | |
public void findChasePath(Point playerPos, Maze theMaze) { | |
Point current; | |
int cost=0; | |
Point nextPoint; | |
//This should be a field | |
chasePath = new LinkedList<Point>(); | |
//Comparator with the playerPos as the destination | |
PointComparison compar = new PointComparison(playerPos); | |
PriorityQueue<Point> pathChoice = new PriorityQueue<Point>(10, compar); | |
LinkedList<Point> closedChoice = new LinkedList<Point>(); | |
pathChoice.add(getCurLoc()); | |
/* | |
* @TODO Refactor this thing | |
*/ | |
//while path to player hasn't been found | |
while (!pathChoice.peek().equals(playerPos)) { | |
current = pathChoice.poll(); | |
closedChoice.add(current); | |
//Loop through neighbour nodes | |
for (int x=-1; x<3; x++) { | |
for (int y=-1; y<3; y++) { | |
//Ensure diagonals are skipped | |
if (!theMaze.checkDiagonals((int)current.getX(), (int)current.getY(), x, y)) { | |
cost = compar.findWeight(current); | |
nextPoint = new Point((int)current.getX()+x, (int)current.getY()+y); | |
//Ensure neighbour isn't a wall | |
if (!theMaze.isCellPassable((int)nextPoint.getX(), (int)nextPoint.getY())) { | |
break; | |
} | |
//Check to see if neighbour is a better candidate than current | |
if (pathChoice.contains(nextPoint) && compar.findWeight(nextPoint) > cost) { | |
closedChoice.add(nextPoint); | |
//Add neighbour path if its better | |
pathChoice.remove(nextPoint); | |
pathChoice.add(current); | |
chasePath.add(nextPoint); | |
} else if (compar.findWeight(closedChoice.peek()) < cost) { | |
pathChoice.add(closedChoice.peek()); | |
//Ensure a point in closed is not closer to goal | |
closedChoice.remove(nextPoint); | |
}else if (!closedChoice.contains(nextPoint) && !pathChoice.contains(nextPoint)) { | |
//When point is not in either list | |
pathChoice.add(nextPoint); | |
//Add to path for chasing | |
//chasePath.add(nextPoint); | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment