74 lines
2.4 KiB
Java
74 lines
2.4 KiB
Java
package ruscz.game.gameOfProd.Scripts;
|
|
|
|
import ruscz.game.gameOfProd.AStar.*;
|
|
import ruscz.game.gameOfProd.Cells.TypeOfCell;
|
|
import ruscz.game.gameOfProd.Map.Map;
|
|
|
|
import java.util.LinkedList;
|
|
import java.util.List;
|
|
|
|
/**
|
|
* This class handles translation between the output of A* algorithm and our internal movement directions
|
|
*/
|
|
public class PathFinder {
|
|
private final Map map;
|
|
|
|
private static final int MAX_STEPS = 200;
|
|
|
|
public PathFinder(Map map) {
|
|
this.map = map;
|
|
}
|
|
|
|
/**
|
|
* Finds path with A* algorithm and translates it to directions using Direction enumeration
|
|
* @param startX is starting X value
|
|
* @param startY is starting Y value
|
|
* @param endX is ending X value
|
|
* @param endY is ending Y value
|
|
* @return list of directions for NPC
|
|
*/
|
|
public LinkedList<Direction> getWayWithCollision(int startX, int startY, int endX, int endY) {
|
|
AStar aStar = new AStar(map.getMapArray().length, map.getMapArray()[0].length, new Node(startX, startY), new Node(endX, endY));
|
|
LinkedList<Direction> directions = new LinkedList<>();
|
|
|
|
for (int i = 0; i < map.getMapArray().length; i++) {
|
|
for (int j = 0; j < map.getMapArray()[0].length; j++) {
|
|
if (map.getMapArray()[i][j] == TypeOfCell.BLOCK || (map.getMapArray()[i][j] == TypeOfCell.EVENT && !map.isTriggerCell(i, j))) {
|
|
aStar.setBlock(i, j);
|
|
}
|
|
}
|
|
}
|
|
|
|
List<Node> nodeList = aStar.findPath();
|
|
if (nodeList.size() == 0) {
|
|
return directions;
|
|
}
|
|
Node nowNode = nodeList.get(0);
|
|
if (nodeList.get(nodeList.size() - 1).getG() > MAX_STEPS)
|
|
return new LinkedList<>();
|
|
|
|
for (Node node : nodeList) {
|
|
if (nowNode == node) {
|
|
continue;
|
|
}
|
|
|
|
if (nowNode.getG() > MAX_STEPS)
|
|
return new LinkedList<>();
|
|
|
|
if (node.getRow() - nowNode.getRow() == 1) {
|
|
directions.add(Direction.RIGHT);
|
|
}
|
|
if (node.getRow() - nowNode.getRow() == -1) {
|
|
directions.add(Direction.LEFT);
|
|
}
|
|
if (node.getCol() - nowNode.getCol() == 1) {
|
|
directions.add(Direction.DOWN);
|
|
}
|
|
if (node.getCol() - nowNode.getCol() == -1) {
|
|
directions.add(Direction.UP);
|
|
}
|
|
nowNode = node;
|
|
}
|
|
return directions;
|
|
}
|
|
} |