cocos2d - JS A*演算法

Cleve_baby發表於2018-07-06

建立地圖 ( map物件 ) :

var map = {
       rows : 5,
       cols : 5,
       arr : [
           [0,0,1,0,0],
           [0,0,1,0,0],
           [0,1,0,0,0],
           [0,1,0,1,0],
           [0,0,0,1,0],
       ]
   }
   var result = this.searchRoad(map,0,0,4,4)
   cc.log(result)

計算獲得移動路徑陣列 :

    //其中的MAP.arr是二維陣列
    searchRoad :function (MAP, start_x, start_y, end_x, end_y){
        var openList=[],    //開啟列表
            closeList=[],   //關閉列表
            result=[],      //結果陣列
            result_index;   //結果陣列在開啟列表中的序號
        openList.push({x:start_x,y:start_y,G:0});//把當前點加入到開啟列表中,並且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) &&          //判斷是否在關閉列表中
                    MAP.arr[item.x][currentPoint.y] != 1 &&   //判斷之間是否有障礙物,如果有障礙物是過不去的
                    MAP.arr[currentPoint.x][item.y] != 1){
                    //g 到父節點的位置
                    //如果是上下左右位置的則g等於10,斜對角的就是14
                    var g = currentPoint.G + ((currentPoint.x - item.x) * (currentPoint.y - item.y) == 0 ? 10 : 14);
                    if (!existList(item, openList)) {       //如果不在開啟列表中
                        //計算H,通過水平和垂直距離進行確定
                        item['H'] = Math.abs(end_x - item.x) * 10 + Math.abs(end_y - item.y) * 10;
                        item['G'] = g;
                        item['F'] = item.H + item.G;
                        item['parent'] = currentPoint;
                        openList.push(item);
                    }
                    else {                                  //存在在開啟列表中,比較目前的g值和之前的g的大小
                        var index = existList(item, openList);
                        //如果當前點的g更小
                        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);//這一步是為了迴圈回去的時候,找出 F 值最小的, 將它從 "開啟列表" 中移掉
        }while(!(result_index=existList({x:end_x,y:end_y},openList)));

        //判斷結果列表是否為空
        if(!result_index) 
        {
            result = [];
        }
        else 
        {
            var currentObj=openList[result_index];
            do{
                //把路勁節點新增到result當中
                result.unshift({
                    x:currentObj.x,
                    y:currentObj.y
                });
                currentObj=currentObj.parent;
            }while (currentObj.x != start_x || currentObj.y != start_y);

        }
        return result;

    },
  • 全域性方法 :

//用F值對陣列排序
function sortF(a,b){
    return b.F - a.F;
}

//獲取周圍八個點的值
function SurroundPoint(curPoint){
    var x = curPoint.x,
        y = 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;
}

完整 cocos2d - JS 例項 :

(複製可以直接使用 只需要在resource裡有三種圖片即可) 
這裡寫圖片描述

  • 0 : 為可走路徑
  • 1 : 為不可走路徑
  • 9 : 為主角

完整程式碼 :

//用F值對陣列排序
function sortF(a,b){
    return b.F - a.F;
}

//獲取周圍八個點的值
function SurroundPoint(curPoint){
    var x = curPoint.x,
        y = 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;
}

var map = {
    rows : 5,
    cols : 5,
    arr : [
        [0,0,1,0,0],
        [0,0,1,0,0],
        [0,1,0,0,0],
        [0,1,0,1,0],
        [0,0,0,1,0],
    ]
}

var MyPos = null;
var MySprite = null;
var HelloWorldLayer = cc.Layer.extend({
    ctor:function () {
        this._super();
        this.Astar();
    },
    call_Back: function(event,touch){
        cc.log("touch",event._parent.AstarX,event._parent.AstarY)
        var endX = event._parent.AstarX,
            endY = event._parent.AstarY;
        var result = this.searchRoad(map,MyPos.x,MyPos.y,endX,endY);

        this.schedule(function(){
            var road = result.shift()
            if(road)
            {
                var action = cc.moveTo(0.24,240+34*road.y,350-36*road.x);
                MySprite.runAction(action);
                MyPos = cc.p(road.x,road.y);
            }
        },0.25)
    },


    Astar: function(){
        MyPos = cc.p(0,0);
        for(var i = 0; i < map.rows; i++)
        {
            for(var j = 0; j < map.cols; j++)
            {
                var temp = new cc.Menu(new cc.MenuItemImage("res/"+map.arr[i][j]+".png", "res/"+map.arr[i][j]+".png", this.call_Back, this));
                temp.setPosition(240+34*j,350-36*i);
                temp.AstarX = i;
                temp.AstarY = j;
                this.addChild(temp);

                if(i == 0 && j == 0)
                {
                    var temp = new cc.Sprite("res/9.png")
                    MySprite = temp;
                    temp.setPosition(240+34*j,350-36*i);
                    this.addChild(temp,1000);
                }
            }
        }
    },

    //其中的MAP.arr是二維陣列
    searchRoad :function (MAP, start_x, start_y, end_x, end_y){
        var openList=[],    //開啟列表
            closeList=[],   //關閉列表
            result=[],      //結果陣列
            result_index;   //結果陣列在開啟列表中的序號
        openList.push({x:start_x,y:start_y,G:0});//把當前點加入到開啟列表中,並且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) &&          //判斷是否在關閉列表中
                    MAP.arr[item.x][currentPoint.y] != 1 &&   //判斷之間是否有障礙物,如果有障礙物是過不去的
                    MAP.arr[currentPoint.x][item.y] != 1){
                    //g 到父節點的位置
                    //如果是上下左右位置的則g等於10,斜對角的就是14
                    var g = currentPoint.G + ((currentPoint.x - item.x) * (currentPoint.y - item.y) == 0 ? 10 : 14);
                    if (!existList(item, openList)) {       //如果不在開啟列表中
                        //計算H,通過水平和垂直距離進行確定
                        item['H'] = Math.abs(end_x - item.x) * 10 + Math.abs(end_y - item.y) * 10;
                        item['G'] = g;
                        item['F'] = item.H + item.G;
                        item['parent'] = currentPoint;
                        openList.push(item);
                    }
                    //存在在開啟列表中,比較目前的g值和之前的g的大小
                    else
                    {
                        var index = existList(item, openList);
                        //如果當前點的g更小
                        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;
            }
            //這一步是為了迴圈回去的時候,找出 F 值最小的, 將它從 "開啟列表" 中移掉
            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當中
                result.unshift({
                    x:currentObj.x,
                    y:currentObj.y
                });
                currentObj=currentObj.parent;
            }while (currentObj.x != start_x || currentObj.y != start_y);
        }
        return result;
    },
});

var HelloWorldScene = cc.Scene.extend({
    onEnter:function () {
        this._super();
        var layer = new HelloWorldLayer();
        this.addChild(layer);

    }
});

相關文章