Talk is cheap, show me the code
寻路算法的主体逻辑
算法的输入:起点,终点,地图信息
算法的输出:从起点到终点的路径
var grid = [
[ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1] ,
[ 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1] ,
[ 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1] ,
[ 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1] ,
[ 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1] ,
[ 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1] ,
[ 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1] ,
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
];
function searchRoad(start, end, MAP) {
var start_x = Number(start.x);
var start_y = Number(start.y);
var end_x = Number(end.x);
var end_y = Number(end.y);
var openList = [],
closeList = [],
result = [],
result_index;
var D = 10;
var ArcD = 14;
openList.push({x:start_x,y:start_y,G:0});
do {
var currentPoint = openList.pop();
closeList.push(currentPoint);
var surroundPoint = SurroundPoint(currentPoint);
for(var i in surroundPoint) {
var item = surroundPoint[i];
if (
item.x >= 0 &&
item.y >= 0 &&
item.x < MAP.rows &&
item.y < MAP.cols &&
MAP.arr[item.x][item.y] != 1 &&
!existList(item, closeList)
) {
var g = currentPoint.G + ((currentPoint.x - item.x) * (currentPoint.y - item.y) == 0 ? D : ArcD);
if (!existList(item, openList)) {
item['H'] = Heuristics(item, end_x, end_y, D, ArcD);
item['G'] = g;
item['F'] = item.H + item.G;
item['parent'] = currentPoint;
openList.push(item);
}
else {
var index = existList(item, openList);
if (g < openList[index].G) {
openList[index].parent = currentPoint;
openList[index].G = g;
openList[index].F = g + openList[index].H;
}
}
}
}
if(openList.length == 0) {
break;
}
openList.sort(sortF);
}while(!(result_index = existList({x:end_x,y:end_y},openList)));
if(!result_index) {
result = [];
}
else {
var currentObj = openList[result_index];
do {
result.unshift({
x:currentObj.x,
y:currentObj.y
});
currentObj = currentObj.parent;
}while (currentObj.x != start_x || currentObj.y != start_y);
}
return {
path: result,
openList: openList
};
}
辅助方法,有排序,查找临近节点,判断某个节点是否在列表中以及启发式函数计算H值
function sortF(a,b) {
return b.F - a.F;
}
function SurroundPoint(curPoint) {
var x = Number(curPoint.x), y = Number(curPoint.y);
return [
{x:x-1,y:y-1},
{x:x,y:y-1},
{x:x+1,y:y-1},
{x:x+1,y:y},
{x:x+1,y:y+1},
{x:x,y:y+1},
{x:x-1,y:y+1},
{x:x-1,y:y}
];
}
function existList(point,list) {
for(var i in list) {
if(point.x==list[i].x && point.y==list[i].y) {
return i;
}
}
return false;
}
function Heuristics(item, end_x, end_y, D, D2) {
var dx = Math.abs(item.x - end_x);
var dy = Math.abs(item.y - end_y);
return D * (dx + dy) + (D2 - 2 * D) * Math.min(dx, dy);
}