A*寻路算法

参考:

http://rangercyh.blog.51cto.com/1444712/792044

http://www.cppblog.com/christanxw/archive/2006/04/07/5126.html

http://dev.gameres.com/Program/Abstract/a8first_2.htm

http://www.chinaai.org/programming/algorithm/a-shortest-path.html (里面有云风大神的A*算法代码)

http://qinysong.iteye.com/blog/678941 (在此把这个算法称作B* 寻路算法(Branch Star 分支寻路算法,且与A*对应),本算法适用于游戏中怪物的自动寻路,其效率远远超过A*算法,经过测试,效率是普通A*算法的几十上百倍。 )

#pragma once
#include <list>
#include <vector>
#include <cassert>

#define OPENLIMIT 100
#define CLOSELIMIT 200

//容器中的node需要根据f_value排序从小到大
struct Node
{
    int x;
    int y;
    int g_value;
    int h_value;
    int f_value;
    Node* parent;
    Node():x(0), y(0), g_value(0), h_value(0), f_value(0), parent(0){}
};

class CAStar
{
public:
    CAStar() {}
    ~CAStar();

    void Init(int width, int height, std::string file, 
        int startX, int startY, int endX, int endY);

    bool FindPath();

    void GetFoundPath(std::vector<int>& vec);

    //连续3个以上的路径点在一条直线上,则去掉中间几个点;
    void OptimizePath(std::vector<int>& vec);

private:
    bool TryTile(int pos, int curPos);

    int tile_num(int x, int y) const 
    {
        return y * width_ + x;
    }

    int tile_x(int n) const
    {
        return n % width_;
    }

    int tile_y(int n) const
    {
        return n / width_;
    }

    int GetGValueAtPos(int pos) const
    {
        if (pos == 1)
            return 0;
        return pNodes_[pos]->parent->g_value + 1;
    }

    int GetHValueAtPos(int x, int y) const
    {
        return abs(x - endX_) + abs(y - endY_);
    }

    bool IsReachable(int pos) const
    {
        int x = tile_x(pos);
        int y = tile_y(pos);
        return x >= 0 && x < width_ && y >= 0 && y< height_;
    }

private:
    int width_;
    int height_;

    int startX_;
    int startY_;
    int endX_;
    int endY_;

    std::vector<int> walkMask_;  // 地图的阻挡信息保存成width_*height_的一维数组
    std::vector<Node*> pNodes_;  //保存父子节点关系;

    std::list<int> openList_;
    std::list<int> closeList_;

    std::vector<int> foundPath_;
};

 

#include "AStar.h"

int main()
{
    CAStar aStar;
    aStar.Init(10, 10, "map.txt", 2, 2, 4, 6);
    bool bFound = aStar.FindPath();
    if (!bFound)
    {
        cout<<"can not find path!"<<endl;
        system("pause");
        return -1;
    }

    std::vector<int> vec;
    aStar.GetFoundPath(vec);
    cout<<"path point num:"<<vec.size()<<endl;
    for (int i=0; i<vec.size(); ++i)
    {
        int x = vec[i] % 10;
        int y = vec[i] / 10;
        cout<<y<<""<<x<<""<<endl;
    }

    aStar.OptimizePath(vec);
    cout<<"after optimize, path point num: "<<vec.size()<<endl;
    for (int i=0; i<vec.size(); ++i)
    {
        int x = vec[i] % 10;
        int y = vec[i] / 10;
        cout<<y<<""<<x<<""<<endl;
    }

    system("pause");
}

 

 

posted @ 2012-07-09 16:16  小 楼 一 夜 听 春 雨  阅读(783)  评论(0编辑  收藏  举报