【步兵 c++】教科书般的A*寻路算法 by EOS.
好久之前写的了,拿出来稍微整理了一下,看上去一份教科书上的一样标准=。=
没人没有任何技巧性的东西,感觉好悲哀。唯一的亮度就是,功能写好后,
接口封装的还是比较漂亮的~
好了,500来行的代码,看起来,应该不会很困难,废话不多说,
还是老样子,原理自行百度,直接上代码=、=
哦,不对,先上张图。给你点动力~
这是不走斜线版的=。=,蓄力已满,开始看代码吧
头文件
#pragma once
#include <list>
typedef unsigned char TileType;
typedef struct AStarPoint
{
int i,j;
}AStarPoint;
typedef struct AStarNode
{
//节点结构体
int f,g,h;
int row; //该节点所在行
int col; //该节点所在列
AStarPoint direct;//parent节点要移动的方向就能到达本节点
struct AStarNode * parent;
}AStarNode;
typedef struct AStarList
{
//OPEN CLOSED 表结构体
AStarNode * npoint;
struct AStarList * next;
}AStarList;
#define MAXROW 100
#define MAXCOL 100
class AStar
{
public:
AStar();
~AStar();
static AStar* getInstance();
static void destroy();
static std::list<AStarPoint> run(TileType inMap[MAXROW][MAXCOL], int inRow, int inCol, int StartX, int StartY, int EndX, int EndY);
void PrintMap();//测试用
AStarNode* getNodeFromOpen();
void pushOpen(AStarNode * suc);
void pushClosed(AStarNode * suc);
int getH(int row, int col);
int getRowPosition(int y);
int getColPosition(int x);
AStarNode* checkOpen(int row, int col);
bool isInClose(int row, int col);
void creatNextLapNode(AStarNode *bestNode, int row, int col,int G_OFFSET);
bool isCanMove(int col, int row);
void seachSeccessionNode(AStarNode *bestNode);
std::list<AStarPoint> findPath(TileType inMap[MAXROW][MAXCOL], int inRow, int inCol, int StartX, int StartY, int EndX, int EndY);
private:
int map[MAXROW][MAXCOL];
int rows;
int cols;
int destinationRow;
int destinationCol;
};
源文件
#include "AStar.h"
AStar::AStar()
{
}
AStar::~AStar()
{
}
static AStar* m_only_AStar = nullptr;
AStar* AStar::getInstance()
{
if (!m_only_AStar)
{
m_only_AStar = new AStar;
}
return m_only_AS