Cocos2dx A * algorithm, cocos2dx Algorithm

Source: Internet
Author: User

Cocos2dx A * algorithm, cocos2dx Algorithm

The header file and source file can be copied to the project! Have fun

Cocos2dx 3.2 works the same way

The blue point is the map

A dark blue dot is an obstacle.

The green point is the path.

Dark green points are searched points.

The red points are the walking points by path.



Dijkstra algorithm will find that the path is the shortest, but there are many searched paths (slow computing speed)



The best priority search algorithm will find that there are fewer paths to be searched (the computing speed is improved), but it takes a lot of detours.



Combined with the above two algorithms, the astar algorithm finds the shortest path, with fewer searched paths.



# Ifndef _ HELLOWORLD_SCENE_H __# define _ HELLOWORLD_SCENE_H __# include "cocos2d. h "# include" vector "using namespace std; USING_NS_CC; class PathSprite: public cocos2d: Sprite // inherit the Sprite class, because you need to add some other variables in It {PathSprite (): sprite () {m_parent = NULL; m_child = NULL; m_costToSource = 0; m_FValue = 0 ;}; public: static PathSprite * create (const char * ch) {PathSprite * pRet = new PathSprite (); if (pRet) {pRet-> ini TWithFile (ch); pRet-> autorelease (); return pRet;} else {delete pRet; pRet = NULL; return NULL ;}} PathSprite * m_parent; // parent node PathSprite * m_child; // child node float m_costToSource; // The distance from the start point to int m_x; // map coordinate int m_y; float m_FValue ;}; class PathSearchInfo // pathing class (mainly responsible for pathing parameters and logic) {public: static int m_startX; // start point static int m_startY; static int m_endX; // end point: static int m_endY; static vector <PathSprite *> m_openLis T; // open list (containing adjacent nodes) static vector <PathSprite *> m_inspectList; // detection list (containing nodes except obstacles) static vector <PathSprite *> m_pathList; // path list static void barrierTest (vector <PathSprite *> & pathList, int x, int y) // simulate obstacle {PathSprite * _ z = getObjByPointOfMapCoord (pathList, x, y); if (_ z) {_ z-> setColor (ccColor3B: MAGENTA); removeObjFromList (pathList, _ z);} static float calculateTwoObjDistance (PathSprite * obj1, Pa ThSprite * obj2) // calculate the distance between two objects {// float _ offsetX = obj1-> m_x-obj2-> m_x; // float _ offsetY = obj1-> m_y-obj2-> m_y; // return sqrt (_ offsetX * _ offsetX + _ offsetY * _ offsetY ); float _ x = abs (obj2-> m_x-obj1-> m_x); float _ y = abs (obj2-> m_y-obj1-> m_y ); return _ x + _ y;} static void inspectTheAdjacentNodes (PathSprite * node, PathSprite * adjacent, PathSprite * endNode) // place adjacent nodes into open nodes {if (adjacent) {f Loat _ x = abs (endNode-> m_x-adjacent-> m_x); float _ y = abs (endNode-> m_y-adjacent-> m_y); float F, G, h1, H2, H3; adjacent-> m_costToSource = node-> m_costToSource + calculateTwoObjDistance (node, adjacent); // obtain the Accumulated distance G = adjacent-> m_costToSource; // three algorithms, I think H2 is good. H1 = _ x + _ y; H2 = hypot (_ x, _ y); H3 = max (_ x, _ y ); # if 1 // A * algorithm = Dijkstra algorithm + optimal Priority Search F = G + H2; # endif # if 0 // Dijkstra algorithm F = G; # endif # if 0/ /Optimal search for F = H2; # endif adjacent-> m_FValue = F; adjacent-> m_parent = node; // set the parent node adjacent-> setColor (Color3B: ORANGE ); // set the searched node to orange node-> m_child = adjacent; // set the subnode PathSearchInfo: removeObjFromList (PathSearchInfo: m_inspectList, adjacent ); // Delete the detected vertex from the detection list PathSearchInfo: m_openList.push_back (adjacent); // Add it to the open list} static PathSprite * getMinPathFormOpenList () // obtain the minimum path value from the open node {if (m_openList.size ()> 0) {PathSprite * _ sp = * m_openList.begin (); for (vector <PathSprite *>: iterator iter = m_openList.begin (); iter! = M_openList.end (); iter ++) {if (* iter)-> m_FValue <_ sp-> m_FValue) {_ sp = * iter;} return _ sp ;} else {return NULL ;}} static PathSprite * getObjByPointOfMapCoord (vector <PathSprite *> & spriteVector, int x, int y) // obtain the object by vertex {for (int I = 0; I <spriteVector. size (); I ++) {if (spriteVector [I]-> m_x = x & spriteVector [I]-> m_y = y) {return spriteVector [I] ;}} return NULL ;} static bool remove ObjFromList (vector <PathSprite *> & spriteVector, PathSprite * sprite) // removes objects from the container {for (vector <PathSprite * >:: iterator iter = spriteVector. begin (); iter! = SpriteVector. end (); iter ++) {if (* iter = sprite) {spriteVector. erase (iter); return true ;}} return false ;}; class HelloWorld: public cocos2d: Layer {public: // there's no 'id' in cpp, so we recommend returning the class instance pointer static cocos2d: Scene * createScene (); // Here's a difference. method 'init 'in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone virtual bool init (); // a selector callback void menuCloseCallback (cocos2d: Ref * pSender ); // implement the "static create ()" method manually CREATE_FUNC (HelloWorld); bool onTouchBegan (Touch * touch, Event * event); void onTouchMoved (Touch * touch, event * event); void onTouchEnded (Touch * touch, Event * event); void calculatePath (); // calculate the path void drawPath (); // draw the path vector <PathSprite *> m_mapList; // map void clearPath (); // clear the path PathSprite * m_player; // The character is used to demonstrate the walk int m_playerMoveStep; // The current itinerary of the character void playerMove (); // move the character}; # endif // _ HELLOWORLD_SCENE_H __
# Include "HelloWorldScene. h "vector <PathSprite *> PathSearchInfo: m_openList; vector <PathSprite *> PathSearchInfo: m_inspectList; vector <PathSprite *> PathSearchInfo: m_pathList; int PathSearchInfo: m_startX; int PathSearchInfo: m_startY; int PathSearchInfo: m_endX; int PathSearchInfo: m_endY; Scene * HelloWorld: createScene () {// 'Scene 'is an autorelease object auto scene = scene: create (); // 'player' is Autorelease object auto layer = HelloWorld: create (); // add layer as a child to scene-> addChild (layer); // return the scene return scene ;} // on "init" you need to initialize your instancebool HelloWorld: init () {// 1. super init first if (! Layer: init () {return false;} Size visibleSize = Director: getInstance ()-> getVisibleSize (); Vec2 origin = Director: getInstance () -> getVisibleOrigin (); Size winSize = Director: getInstance ()-> getWinSize (); /// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelwon o Bject auto listener = EventListenerTouchOneByOne: create (); listener-> setSwallowTouches (true); listener-> onTouchBegan = CC_CALLBACK_2 (HelloWorld: onTouchBegan, this ); listener-> onTouchMoved = CC_CALLBACK_2 (HelloWorld: ontouchmovable, this); listener-> onTouchEnded = CC_CALLBACK_2 (HelloWorld: onTouchEnded, this); _ eventDispatcher-> listener (listener, this); // simulate the upper-left corner of a map (0, 0) it is used to simulate the tiledmap width of each block as 1 int _ width = 25; int _ heigth = 15; for (int I = 0; I <_ heigth; I ++) {for (int j = 0; j <_ width; j ++) {PathSprite * _ sp = PathSprite: create ("CloseNormal.png "); _ sp-> m_x = j; _ sp-> m_y = I; Size _ size = _ sp-> getContentSize (); _ sp-> setPosition (CCPoint (j * _ size. width + 100,-I * _ size. height + 600); m_mapList.push_back (_ sp); this-> addChild (_ sp) ;}// sets the obstacle // for (int I = 0; I <_ heigth * _ width/2; I ++) // {// int _ x = CCRANDOM_0_1 () * _ width; // int _ y = CCRANDOM_0_1 () * _ heigth; // if (_ x = 0 & _ y = 0) {// continue; //} // PathSearchInfo: barrierTest (m_mapList, _ x, _ y); //} for (int I = 0; I <10; I ++) {PathSearchInfo:: barrierTest (m_mapList, 5 + I, 10); PathSearchInfo: barrierTest (m_mapList, 15, I + 1);} // PathSprite: getObjByPointOfMapCoord (m_inspectList, 2, 5) -> removeFr OmParent (); // set the start and end PathSearchInfo: m_startX = 0; PathSearchInfo: m_startY = 0; PathSearchInfo: m_endX = 4; PathSearchInfo: m_endY = 9; m_player = PathSprite: create ("CloseSelected1.png"); m_player-> setColor (Color3B: RED); this-> addChild (m_player); m_player-> m_x = PathSearchInfo :: m_startX; m_player-> m_y = PathSearchInfo: m_startY; m_player-> setPosition (PathSearchInfo: getObjByPointOfMapCoord (m_ma PList, PathSearchInfo: m_startX, PathSearchInfo: m_startY)-> getPosition (); return true;} void HelloWorld: calculatePath () {// get the Start Node PathSprite * _ sp = PathSearchInfo: getObjByPointOfMapCoord (PathSearchInfo: m_inspectList, PathSearchInfo: m_startX, PathSearchInfo: m_startY ); // obtain the Start Node PathSprite * _ endNode = PathSearchInfo: getObjByPointOfMapCoord (PathSearchInfo: m_inspectList, PathSearchInfo: m_e NdX, PathSearchInfo: m_endY); // set the distance from the start point to 0 _ sp-> m_costToSource = 0; _ sp-> m_FValue = 0; // Delete the detected vertex from the detection list PathSearchInfo: removeObjFromList (PathSearchInfo: m_inspectList, _ sp); // Add it to the open list PathSearchInfo :: m_openList.push_back (_ sp); PathSprite * _ node = NULL; while (true) {// get the point closest to the start point _ node = PathSearchInfo: getMinPathFormOpenList (); if (! _ Node) {// The path break cannot be found;} // Delete the computed vertex from the open list PathSearchInfo: removeObjFromList (PathSearchInfo: m_openList, _ node ); int _ x = _ node-> m_x; int _ y = _ node-> m_y; // if (_ x = PathSearchInfo: m_endX & _ y = PathSearchInfo:: m_endY) {break;} // checks whether adjacent nodes in eight directions can be placed in the open list. PathSprite * _ adjacent = PathSearchInfo: getObjByPointOfMapCoord (PathSearchInfo: m_inspectList, _ x + 1, _ y + 1); PathSearchInfo: inspectTheAdja CentNodes (_ node, _ adjacent, _ endNode); _ adjacent = PathSearchInfo: getObjByPointOfMapCoord (PathSearchInfo: m_inspectList, _ x + 1, _ y); PathSearchInfo :: inspectTheAdjacentNodes (_ node, _ adjacent, _ endNode); _ adjacent = PathSearchInfo: getObjByPointOfMapCoord (PathSearchInfo: m_inspectList, _ x + 1, _ Y-1); PathSearchInfo :: inspectTheAdjacentNodes (_ node, _ adjacent, _ endNode); _ adjacent = PathSearchInfo: get ObjByPointOfMapCoord (PathSearchInfo: m_inspectList, _ x, _ y-1); PathSearchInfo: inspectTheAdjacentNodes (_ node, _ adjacent, _ endNode); _ adjacent = PathSearchInfo :: aggregate (PathSearchInfo: m_inspectList, _ x-1, _ y-1); PathSearchInfo: inspectTheAdjacentNodes (_ node, _ adjacent, _ endNode); _ adjacent = PathSearchInfo :: getObjByPointOfMapCoord (PathSearchInfo: m_inspectList, _ x-1, _ y); Pat HSearchInfo: inspectTheAdjacentNodes (_ node, _ adjacent, _ endNode); _ adjacent = PathSearchInfo: equals (PathSearchInfo: m_inspectList, _ x-1, _ y + 1 ); pathSearchInfo: inspectTheAdjacentNodes (_ node, _ adjacent, _ endNode); _ adjacent = PathSearchInfo: Unknown (PathSearchInfo: m_inspectList, _ x, _ y + 1); PathSearchInfo :: inspectTheAdjacentNodes (_ node, _ adjacent, _ endNode);} wh Ile (_ node) {// PathSprite * _ sp = node; PathSearchInfo: m_pathList.insert (PathSearchInfo: m_pathList.begin (), _ node ); _ node = _ node-> m_parent;} void HelloWorld: drawPath () {for (vector <PathSprite * >:: iterator iter = PathSearchInfo: m_pathList.begin (); iter! = PathSearchInfo: m_pathList.end (); iter ++) {(* iter)-> setColor (ccColor3B: GREEN) ;}} bool HelloWorld: onTouchBegan (Touch * touch, event * event) {// clear the previous path clearPath (); auto nodePosition = convertToNodeSpace (touch-> getLocation (); log ("% f, % f", nodePosition. x, nodePosition. y); for (int I = 0; I <PathSearchInfo: m_inspectList.size (); I ++) {PathSprite * _ sp = PathSearchInfo: m_inspectList [I]; if (_ Sp-> getBoundingBox (). containsPoint (nodePosition) {// obtain the touch point and set it to PathSearchInfo: m_endX = _ sp-> m_x; PathSearchInfo: m_endY = _ sp-> m_y; // calculate the path calculatePath (); // draw the path drawPath (); playerMove () ;}return true;} void HelloWorld: onTouchMoved (Touch * touch, Event * event) {// If it weren't for the TouchDispatcher, you woshould need to keep a reference // to the touch from touchBegan and check that the c Urrent touch is the same // as that one. // Actually, it wocould be even more complicated since in the Cocos dispatcher // you get Sets instead of 1 UITouch, so you 'd need to loop through the set // in each touchXXX method .} void HelloWorld: onTouchEnded (Touch * touch, Event * event) {} void HelloWorld: menuCloseCallback (Ref * pSender) {# if (CC_TARGET_PLATFORM = platform) | (CC_TARGET_PLATFORM = CC_PLATFORM_WINRT) MessageBox ("You pressed the close button. windows Store Apps do not implement a close button. "," Alert "); return; # endif Director: getInstance ()-> end (); # if (CC_TARGET_PLATFORM = CC_PLATFORM_IOS) exit (0 ); # endif} void HelloWorld: clearPath () {for (vector <PathSprite * >:: iterator iter = m_mapList.begin (); iter! = M_mapList.end (); iter ++) {(* iter)-> setColor (ccColor3B: WHITE); (* iter)-> m_costToSource = 0; (* iter) -> m_FValue = 0; (* iter)-> m_parent = NULL; (* iter)-> m_child = NULL ;} // put the map with the obstacle removed into the detection list. PathSearchInfo: m_inspectList = m_mapList; PathSearchInfo: m_openList.clear (); PathSearchInfo: m_pathList.clear (); PathSearchInfo :: m_startX = m_player-> m_x; PathSearchInfo: m_startY = m_player-> m_y; m_player-> stopAllActions (); m_playerMoveStep = 0;} void HelloWorld: playerMove () {m_playerMoveStep ++; if (m_playerMoveStep> = PathSearchInfo: m_pathList.size () {return;} m_player-> m_x = PathSearchInfo: m_pathList [m_playerMoveStep]-> m_x; m_player-> m_y = PathSearchInfo: m_pathList [m_playerMoveStep]-> m_y; m_player-> runAction (Sequence: create (MoveTo: create (0.2, PathSearchInfo :: m_pathList [m_playerMoveStep]-> getPosition (), CallFunc: create (this, SEL_CallFunc (& HelloWorld: playerMove), NULL ));}




A * Practical Significance of Algorithm Application

A * algorithm is A typical Heuristic Search Algorithm in artificial intelligence. To clarify A * algorithm, let me first talk about it.

I. What is a heuristic search algorithm?

Before you start, you need to search for the status space. Status space search. If it is based on a professional point, the problem solving process is represented by the process of searching for this path from the initial state to the target State. In layman's terms, when solving a problem, the process of finding a problem can start from the problem to the result of the problem (as though not popular ). There are many branches in the process of solving the problem, mainly because of the uncertainty of the conditions for solving the problem in the process of solving the problem, which is caused by incompleteness. This constitutes a picture of the many paths for solving the problem, we say this figure is the state space. The problem is actually solved by finding a path in this figure from the beginning to the result. The search process is the state space search.

Frequently Used status space searches have priority in depth and breadth. Breadth First is to find the target layer by layer until the target is found. Depth first searches for one branch in a certain order, and then finds another branch until the target is found. These two algorithms are described in the data structure book. You can refer to these books for more detailed explanations.

One major drawback of the breadth and depth preference search mentioned above is that they all work in a given State Space. This is a suitable algorithm when the state space is not large, but it is not advisable when the state space is large and unpredictable. His efficiency is too low to be completed. Heuristic Search is required here.

Heuristic Search is to evaluate the position of each search in the state space to obtain the best position, and then search until the target. In this way, a large number of fearless search paths can be omitted, and efficiency is mentioned. In heuristic search, location estimation is very important. Different estimates can have different effects. Let's first look at how the valuation is expressed.

In the inspiration, the valuation is represented by the valuation function, for example:

F (n) = g (n) + h (n)

Where f (n) is the estimated function of node n, the actual cost of g (n) from the initial node to the n node in the real state space, h (n) it is the estimated cost of the optimal path from n to the target node. Here, h (n) mainly reflects the inspiration information of search, because g (n) is known. For details, g (n) indicates the priority of search breadth. However, when h (n)> g (n), g (n) can be omitted to improve efficiency. This is deep, and it will not be affected if you don't understand it! Let's continue to look at what A * algorithm is.

Ii. First recognized A * Algorithm

There are actually many heuristic search algorithms, such as local preferred search and best preferred search. Of course, A * is also. These algorithms use heuristic functions, but they have different policies when selecting the best search node. The local preferred search method is to select the "best node" in the search process and discard other sibling nodes. Father's Day points have to be searched continuously. The search results are obvious. Because other nodes are discarded, the best nodes may also be discarded, because the best node for solving is the best at this stage, not necessarily the global best. It is better to give priority to a more intelligent node. When searching, the node is not discarded (unless the node is a dead node ), in each step of evaluation, compare the current node with the previous node's estimated value to get an "Best node ". This effectively prevents the loss of "best node. So what kind of algorithm is A * algorithm? In fact, the * algorithm is also the best priority algorithm. Only some constraints need to be added. When solving some problems, we hope to be able to solve the Shortest Path of the state space search, that is, to solve the problem using the shortest method. A * is doing this! Let's define it first. If an estimate function can find the shortest path, we call it adoption. A * algorithm is the best priority algorithm that can be adopted. The evaluation function of A * algorithm can be expressed:

F' (n) = G' (n) + H' (n)

Here, f' (n) is the evaluation function, and G' (n) is the shortest path value from the start point to the end point, H' (n) it is the inspiration value from n to the target's most Broken Circuit. Because f' (n) is actually unable to pre-Wait... the remaining full text>

AI can take tests. How many other five commonly used heuristic algorithms will not be taught? What are algorithm A and algorithm?

.

Other common algorithms include:

Simulated Annealing Algorithm );
Ant Algorithm );
Tabu Search Algorithm );
Neural Network Algorithm (Neural Network Algorithm );
Genetic Algorithm (Genetic Algorithm)

Hope to help you ^

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.