Hello evryone,
I was couple of days ago working on the Villagers-system. For example: I made a villager that is going to chop a tree and then going back to his home. But for this I needed first some sort of pathfinding. I tried to do something with this tutorial:
A* pathfinding tutorial.
So I coded in what he said (atleast how I think it must be):
[spoiler]
public class FindPath {
private boolean isFindingPath = false;
private List<Point> openList = new ArrayList<Point>();
private List<Point> closedList = new ArrayList<Point>();
private List<Point> path = new ArrayList<Point>();
public List<Point> findPath(Point start, Point end) {
isFindingPath = true;
openList.clear();
closedList.clear();
path.clear();
checkNodesAroundPoint(start);
closedList.add(start);
closedList.add(searchLowestF(start, end));
while(isFindingPath){
checkNodesAroundPoint(searchLowestF(start, end));
closedList.add(searchLowestF(start, end));
}
for (Point p : closedList) {
Game.level.alterTile((int)p.getX(), (int)p.getY(), Tile.POSIONGRASS);
}
return path;
}
public void checkNodesAroundPoint(Point search){
for(int x = (int)search.getX() - 1; x <= (int)search.getX() + 1; x++){
for(int y = (int)search.getY() - 1; y <= (int)search.getY() + 1; y++){
if(!openList.contains(new Point(x,y))){
if(Game.level.isTileWalkable(x, y)){
openList.add(new Point(x,y));
Game.level.alterTile(x, y, Tile.ROCK);
}
}
}
}
}
public Point searchLowestF(Point start, Point end){
Point lowestF = new Point(10, 10);
int lowestFInList = -1;
int g = 0;
int h = 0;
int f = 0;
for (Point p : openList) {
if(p.getX() == start.getX() || p.getY() == start.getY()){
g = 10;
} else {
g = 14;
}
if(p.getX() <= end.getX() && p.getY() <= end.getY()){
h = (((int)end.getX() - (int)p.getX()) + ((int)end.getY() - (int)p.getY()))* 10;
} else if(p.getX() > end.getX() && p.getY() <= end.getY()){
h = (((int)p.getX() - (int)end.getX()) + ((int)end.getY() - (int)p.getY()))* 10;
} else if(p.getX() <= end.getX() && p.getY() > end.getY()){
h = (((int)end.getX() - (int)p.getX()) + ((int)p.getY() - (int)end.getY()))* 10;
} else if(p.getX() > end.getX() && p.getY() > end.getY()){
h = (((int)p.getX() - (int)end.getX()) + ((int)p.getY() - (int)end.getY()))* 10;
}
if(h == 0){
isFindingPath = false;
}
f = g + h;
if(lowestFInList == -1){
lowestFInList = f;
lowestF = p;
} else if(f < lowestFInList){
lowestFInList = f;
lowestF = p;
}
}
return lowestF;
}
}
[/spoiler]
I wrote the code myself, only I think I’ve done many things wrong but atleast I tried it.
The things I had no idea to do was how you can see wich “g” it is (for diagonal 14 and for horizontal, vertical 10.)
and how you can return the good path. (I am now altering the tiles to see what the code is actually doing.)
If someone can explain it to me, how I can reach my 2 goals, then tell it! Don’t send the code if you can explain it. I am still learning java, by writing and thinking myself I learn more then copying other peoples work.
Already thanks!
-RoseSlayer