Repository navigation
Expand file tree
/
Copy pathJps.java
More file actions
78 lines (65 loc) · 2.13 KB
/
Copy pathJps.java
File metadata and controls
78 lines (65 loc) · 2.13 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
package org.bk.ass.path;
import java.util.Collections;
import org.bk.ass.grid.Grid;
/**
* Jump point search. Initialize with a {@link Grid} instance and call {@link #findPath(Position,
* Position)}.
*/
public class Jps {
private final Grid<Boolean> map;
public Jps(Grid<Boolean> map) {
this.map = map;
}
/**
* Searches for a path between start and end. Allows concurrent pathing requests if the map
* implementation allows concurrent queries.
*
* @return a valid path or a path with infinite length if none could be found. Never returns null.
*/
public Result findPath(Position start, Position end) {
return findPath(start, end, Float.MAX_VALUE);
}
public Result findPath(Position start, Position end, float maxLength) {
if (start.equals(end)) {
return new Result(0, Collections.singletonList(start));
}
return new PathFinder(end, map, maxLength).searchFrom(start);
}
private static class PathFinder extends AbstractPathFinder {
private final Grid<Boolean> map;
protected PathFinder(Position target, Grid<Boolean> map, float maxLength) {
super(target, map, maxLength);
this.map = map;
}
@Override
protected Position jumpHorizontal(int px, int py, int dx) {
assert dx != 0;
int x = px + dx;
int a = (map.get(x, py - 1) ? 0 : 1) | (map.get(x, py + 1) ? 0 : 2);
while (map.get(x, py)) {
int b = (map.get(x + dx, py - 1) ? 1 : 0) | (map.get(x + dx, py + 1) ? 2 : 0);
if (x == target.x && py == target.y || (a & b) != 0) {
return new Position(x, py);
}
x += dx;
a = ~b;
}
return null;
}
@Override
protected Position jumpVertical(int px, int py, int dy) {
assert dy != 0;
int y = py + dy;
int a = (map.get(px - 1, y) ? 0 : 1) | (map.get(px + 1, y) ? 0 : 2);
while (map.get(px, y)) {
int b = (map.get(px - 1, y + dy) ? 1 : 0) | (map.get(px + 1, y + dy) ? 2 : 0);
if (px == target.x && y == target.y || (a & b) != 0) {
return new Position(px, y);
}
y += dy;
a = ~b;
}
return null;
}
}
}