diff --git "a/proj/\345\212\250\347\224\273\350\265\204\346\272\220/cocos/roadsearch.cpp" "b/proj/\345\212\250\347\224\273\350\265\204\346\272\220/cocos/roadsearch.cpp" index 35593f3..003bd68 100644 --- "a/proj/\345\212\250\347\224\273\350\265\204\346\272\220/cocos/roadsearch.cpp" +++ "b/proj/\345\212\250\347\224\273\350\265\204\346\272\220/cocos/roadsearch.cpp" @@ -1,26 +1,72 @@ -#include "roadserach.h" +#include "roadsearch.h" void RoadSearch::init() { - for(int i=0; ig = 0; + _startNode->h = euclidian(_startNode); + _startNode->f = _startNode->g + _startNode->h; + return search(); } bool RoadSearch::search() { - + Node* node = _startNode; + while (node != _endNode){ + int startX = MAX(0, node->x-1); + int endX = MIN(Road::WIDTH-1, node->x+1); + int startY = MAX(0, node->y-1); + int endY = MIN(Road::HEIGHT - 1, node->y+1); + for (int i = startX; i <= endX; i++){ + for (int j = startX; j <= endX; j++){ + Node* test = &(_roads[i][j]); + if (test == node || test->pid > 0 || _roads[node->x][test->y].pid > 0 || _roads[test->x][node->y].pid > 0) + continue; + float cost = _straightCost; + if (!(node->x == test->x) || (node->y == test->y)) + cost = _diagCost; + float g = node->g + cost * test->costMultiplier; + float h = euclidian(test); + float f = g + h; + if (isOpen(test) || isClosed(test)){ + test->f = f; + test->g = g; + test->h = h; + test->parent = node; + } else { + test->f = f; + test->g = g; + test->h = h; + test->parent = node; + _open.push_back(test); + } + } + } + _closed.push_back(node); + if (_open.size() == 0){ + return false; + } + // _open.sortOn("f", Array.NUMERIC); + node = _open.removeLastObject() + } + + return true; +} + +float RoadSearch::euclidian(Node* node) +{ + float dx = node->x - _endNode->x; + float dy = node->y - _endNode->y; + return sqrt(dx * dx + dy * dy) * _straightCost; } \ No newline at end of file diff --git "a/proj/\345\212\250\347\224\273\350\265\204\346\272\220/cocos/roadsearch.h" "b/proj/\345\212\250\347\224\273\350\265\204\346\272\220/cocos/roadsearch.h" index 4ca5725..02e32bd 100644 --- "a/proj/\345\212\250\347\224\273\350\265\204\346\272\220/cocos/roadsearch.h" +++ "b/proj/\345\212\250\347\224\273\350\265\204\346\272\220/cocos/roadsearch.h" @@ -2,7 +2,7 @@ #define __ROAD_SERACH_H__ #include "road.h" - +#include /* ½Úµã(node)£º @@ -48,8 +48,8 @@ */ -struct Node{ -public: +struct Node +{ int x,y; float f,g,h; int pid; @@ -67,6 +67,15 @@ class RoadSearch private: Node _roads[Road::WIDTH][Road::HEIGHT]; Node* _startNode; + Node* _endNode; + cocos2d::Array _open; + cocos2d::Array _closed; + + float _straightCost = 1.0f; + float _diagCost = 1.4142135623730951f; + float euclidian(Node* node); + bool isOpen(Node* node); + bool isClosed(Node* node); }; #endif \ No newline at end of file