-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAstar.java
More file actions
120 lines (103 loc) · 3.35 KB
/
Astar.java
File metadata and controls
120 lines (103 loc) · 3.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import java.util.LinkedList;
public class Astar
{
public static LinkedList A_star(Point start, Point goal, WorldModel world)
{
LinkedList<Point> closedset = new LinkedList<>();
OrderedList<Point> openset = new OrderedList<>();
LinkedList<Point> came_from = new LinkedList<>();
openset.insert(start, start.get_f());
start.set_g(0);
start.set_f(start.get_g() + manhattan(start, goal));
while (openset != null)
{
System.out.println(closedset.size());
Point current = openset.head().item;
if(current.equals(goal))
{
return reconstruct_path(came_from, goal);
}
openset.remove(current);
closedset.add(current);
for(Point neighbor : neighbor_nodes(current, world, goal))
{
if(closedset.contains(neighbor))
{
continue;
}
int tentative_gscore = current.get_g() + 1;
if (!(openset.contains(neighbor)) || tentative_gscore < neighbor.get_g())
{
neighbor.set_came_from(current);
neighbor.set_g(tentative_gscore);
neighbor.set_f(neighbor.get_g() + manhattan(neighbor, goal));
if (!openset.contains(neighbor))
{
openset.insert(neighbor, neighbor.get_f());
}
}
}
}
return null;
}
public static LinkedList reconstruct_path(LinkedList came_from, Point current)
{
if (current.get_came_from() != null)
{
came_from.add(current);
}
return came_from;
}
public static OrderedList<Point> get_nodes1(WorldModel world)
{
OrderedList<Point> returnlist = new OrderedList<>();
for(int i = 0; i < world.getNumRows(); i++)
{
for(int j = 0; j < world.getNumCols(); j++)
{
Point node = new Point(j, i);
if (!(world.isOccupied(node)))
{
returnlist.insert(node, node.get_f());
}
}
}
return returnlist;
}
public static LinkedList<Point> get_nodes2(WorldModel world)
{
LinkedList<Point> returnlist = new LinkedList<>();
for(int i = 0; i < world.getNumRows(); i++)
{
for(int j = 0; j < world.getNumCols(); j++)
{
Point node = new Point(j, i);
if (!(world.isOccupied(node)))
{
returnlist.add(node);
}
}
}
return returnlist;
}
public static int manhattan(Point start, Point goal)
{
return ((goal.y - start.y) + (goal.x - start.x));
}
public static LinkedList<Point> neighbor_nodes(Point current, WorldModel world, Point goal)
{
LinkedList<Point> returnlist= new LinkedList<>();
for (Point node : get_nodes2(world))
{
if(MobileAnimatedActor.adjacent(node, current))
{
returnlist.add(node);
}
}
if(MobileAnimatedActor.adjacent(goal, current))
{
returnlist.add(goal);
}
return returnlist;
}
}