All pastes #840474 Raw Edit

Miscellany

public text v1 · immutable
#840474 ·published 2007-12-31 22:31 UTC
rendered paste body
std::vector<Node*> AStar(std::vector<Node*> nodes, // The AStar "open" list
           int start, // start node
           int finish, // goal node
           int maxPathSize // maximum path size. this cuts it off from running
                            // forever.
) {

 // The AStar "closed" list
 std::vector<Node*> path;

 // The "current" node
 Node* current = nodes[start];

 // Points to a spot in the "grid" array, this
 // is the object with the lowest F
 int LowestF = 0;

 // # of times we've run
 int runs = 0;

 // Loop until we're done.
 while(runs < maxPathSize) {

 
  // Loop through nodes and record the "F" element for
  // them.
  for(int i=0; i<nodes.size(); i++) {
   // F = nodePosition - currentNodePosition
   int f = nodes[i]->x + nodes[i]->y;
   f -= ( current->x + current->y );

   if(nodes[i]->walkable) // if we can walk on it
    nodes[i]->f = f; // set it's F var
   else // can't walk on it
    nodes[i]->f = 1000; // so just ignore it
  }

  // Now find the node with the lowest F
  for(int i=0; i<nodes.size(); i++) {

   // Do we have less F than the lowest?
   if(nodes[i]->f < nodes[LowestF]->f)
 
    // Mark us as the lowest
    LowestF = i;
  }
 
  // Now add the "Lowest F" element to the path
  path.push_back(nodes[LowestF]);

  // Set the "current node" to the LowstF node
  current = nodes[LowestF];

  // Now remove the "Lowest F" element from the open
  // list
  nodes.erase( nodes.begin()+LowestF );

  // Add to the # of runs. after maxPathSize runs, we
  // stop.
  runs++;


 }

 // Return the path
 return path;

};