All pastes #840532 Raw Edit

A* Pathfinder

public cpp v1 · immutable
#840532 ·published 2007-12-31 23:50 UTC
rendered paste body
/** Include Headers */#include <vector>#include <iostream>/** Node Class * Just stores X,Y positions and if we're * walkable. */class CNode { protected:  int x,y;  bool walk; public:  CNode(int X, int Y, int W) {   x=X;   y=Y;   walk=W;  }  int getX() { return x; }  int getY() { return y; }  bool getWalkable() { return walk; }  // simple. this is used by the Solver. you can ignore it.  int f; };/** Solver Class * Very simple. create an instance * of one of these, call it's * Solve() function, then call it's * GetPath() function to get the path. */class CSolver { protected:  // The "closed" list (open one is defined in header)  std::vector<CNode*> path; public:  /** Solver Function   * Hand it a list of nodes and a   * start/end node and it'll give   * ya a path.   * start/finish point to places in the   * nodes array   */  void Solve(std::vector<CNode*> nodes, int start, int finish) {   // The "current" node.   CNode* currentNode = nodes[start];   // The "Lowest F" node. points to a spot in the   // open list       int lowestF=0;   // Empty the path, if we used this before   path.clear();   // Loop through every node in the array   for(int foo=0; foo<5; foo++) {    // Reset lowestF    lowestF = 0;    // Loop through each node, setting it's F value(distance)    for(int i=0; i<nodes.size(); i++) {     // F = node position - our position     int f = (nodes[i]->getX() + nodes[i]->getY());     f -= (currentNode->getX() + currentNode->getY());     // Now set the F var     nodes[i]->f = f;    }    // Loop through each node, finding the node    // with the lowest F.    for(int i=0; i<nodes.size(); i++) {     // Lower f then the lowest?     if(nodes[i]->f < nodes[lowestF]->f)      // Set the "lowest f" to us      lowestF = i;    }    // Now, add the 'LowestF' element to closed list    path.push_back(nodes[lowestF]);    // Set the current node to the lowest f node    currentNode = nodes[lowestF];    // And remove the lowestF node from the open list (check if its ok first)    if( lowestF < nodes.size() )      nodes.erase( nodes.begin()+lowestF );  } }; std::vector<CNode*> GetPath() {  return path; }};int main() { CNode* one = new CNode(32,32,true); CNode* two = new CNode(30,30,true); CNode* finish = new CNode(35,35,true); std::vector<CNode*> nodes; nodes.push_back(one); nodes.push_back(two); nodes.push_back(finish); CSolver* solver = new CSolver(); solver->Solve(nodes, 0, 2); std::vector<CNode*> path = solver->GetPath(); for(int i=0; i<path.size(); i++)  std::cout<< path[i]->getX() << " " << path[i]->getY() << std::endl;};