Files
esengine/source/src/AI/Pathfinding/BreadthFirst/UnweightedGridGraph.ts
T

61 lines
1.9 KiB
TypeScript
Raw Normal View History

2020-07-08 15:15:15 +08:00
///<reference path="../../../Math/Vector2.ts" />
2020-06-10 12:23:19 +08:00
/**
* 基本的未加权网格图形用于BreadthFirstPathfinder
*/
2020-07-08 15:15:15 +08:00
class UnweightedGridGraph implements IUnweightedGraph<Vector2> {
private static readonly CARDINAL_DIRS: Vector2[] = [
new Vector2(1, 0),
new Vector2(0, -1),
new Vector2(-1, 0),
new Vector2(0, -1)
2020-06-10 12:23:19 +08:00
];
private static readonly COMPASS_DIRS = [
2020-07-08 15:15:15 +08:00
new Vector2(1, 0),
new Vector2(1, -1),
new Vector2(0, -1),
new Vector2(-1, -1),
new Vector2(-1, 0),
new Vector2(-1, 1),
new Vector2(0, 1),
new Vector2(1, 1),
2020-06-10 12:23:19 +08:00
];
2020-07-08 15:15:15 +08:00
public walls: Vector2[] = [];
2020-06-10 12:23:19 +08:00
private _width: number;
private _hegiht: number;
2020-07-08 15:15:15 +08:00
private _dirs: Vector2[];
private _neighbors: Vector2[] = new Array(4);
2020-06-10 12:23:19 +08:00
constructor(width: number, height: number, allowDiagonalSearch: boolean = false) {
this._width = width;
this._hegiht = height;
this._dirs = allowDiagonalSearch ? UnweightedGridGraph.COMPASS_DIRS : UnweightedGridGraph.CARDINAL_DIRS;
}
2020-07-08 15:15:15 +08:00
public isNodeInBounds(node: Vector2): boolean {
2020-06-10 12:23:19 +08:00
return 0 <= node.x && node.x < this._width && 0 <= node.y && node.y < this._hegiht;
}
2020-07-08 15:15:15 +08:00
public isNodePassable(node: Vector2): boolean {
2020-06-10 12:23:19 +08:00
return !this.walls.firstOrDefault(wall => JSON.stringify(wall) == JSON.stringify(node));
}
2020-07-08 15:15:15 +08:00
public getNeighbors(node: Vector2) {
2020-06-10 12:23:19 +08:00
this._neighbors.length = 0;
this._dirs.forEach(dir => {
2020-07-08 15:15:15 +08:00
let next = new Vector2(node.x + dir.x, node.y + dir.y);
2020-06-10 12:23:19 +08:00
if (this.isNodeInBounds(next) && this.isNodePassable(next))
this._neighbors.push(next);
});
return this._neighbors;
}
2020-07-08 15:15:15 +08:00
public search(start: Vector2, goal: Vector2): Vector2[] {
2020-06-10 12:23:19 +08:00
return BreadthFirstPathfinder.search(this, start, goal);
}
}