Example #1
0
bool AstarMap::findPath(std::vector<MapNode*>& path, int sx, int sy, int tx, int ty)
{
	std::vector<MapNode*> open_stack;

	MapNode* start = getNodeAt(sy,sx);
	MapNode* target = getNodeAt(ty,tx);

	if(start == NULL || target == NULL)
		return false;
	
	start->setOpen(true);
	open_stack.push_back(start);

	while(open_stack.size() > 0){

		std::sort(open_stack.begin(), open_stack.end(), lesser);

		MapNode* node = open_stack.back();

		if(node == target)
			return buildPath(path,target);

		open_stack.pop_back();

		node->setOpen(false);
		node->setClosed(true);

		std::vector<MapNode*> adjacents;

		if(!listAdjacent(adjacents,node))
			continue;

		for(int i = 0; i < adjacents.size(); ++i){

			MapNode* adjacent = adjacents[i];

			if(adjacent->isClosed())
				continue;

			if(adjacent->isLocked())
				continue;

			int check_cost = adjacent->getCostG() + adjacent->isDiagonal(node) ?
				DIAGONAL_MOVE_COST : STRAIGHT_MOVE_COST;

			if(adjacent->isOpen()){

				adjacent->setParent(node);
				adjacent->setCostG(check_cost);

			}else{

				adjacent->setParent(node);
				adjacent->setCostH(adjacent->countHCost(target));
				adjacent->setCostG(check_cost);
				adjacent->setOpen(true);
				open_stack.push_back(adjacent);

			}

		}

	}

	return false;
}