Thread: Pathfinder
View Single Post
  #3  
Old 12-06-2007, 01:21 AM
Novo Novo is offline
[TServerDeveloper]
Join Date: Jun 2006
Posts: 448
Novo will become famous soon enough
PHP Code:
/**
 * Nodes Interface for PathFinder
 *
 * (+) void connect( Node node );
 * (+) void disconnect( Node nodes );
 * (+) Node[] getNodes();
 **/
 
/**
  * This connects a node to the node-list.
  *
  * @param node Node, any object that could be treated as a Node.
  *                If used to connect afterwards, add Node interface!
  **/
public function connect( node )
{
  if ( 
node == null )
    return;
  if ( 
node in this.nodes )
    return;
  
  
this.nodes.add( node );
}

/**
  * This removes a node to the node-list.
  *
  * @param node Node, any object that could be treated as a Node.
  **/

public function disconnect( node )
{
  
this.nodes.remove( node );
}

/**
  * This obtains the nodes that are currently connected to the object.
  *
  * @return Node[] List of nodes attached to object
  **/

public function getNodes()
{
  return 
this.nodes;
}

/**
  * This calculates the shortest distance to a particular node.
  *
  * @return Node[] An ordered list of the nodes that need to be traveled
  *                    to reach given destination.
  **/
function findPath( endNode )
{
  
temp.nodeList.add( {this, new[0]} );
  
temp.nodeIndex = 0;
  while ( 
temp.nodeList.size() > temp.nodeIndex )
  {
    
temp.node = temp.nodeList[ temp.nodeIndex ][0];
    
temp.nodePath = temp.nodeList[ temp.nodeIndex ][1];
    
temp.nodePath.add( temp.node );
    if ( 
temp.node == endNode )
      return 
temp.nodePath;

    for ( 
temp.subnode: node.getNodes() )
    {
      if ( 
temp.subnode in temp.nodeList )
          continue;

      
temp.nodeList.add( { temp.subnode, temp.nodePath } );
    }
    
temp.nodeIndex ++;
  }

  return 
null;
} 
For Stan... And anyone else... It elaborates onto the original code and encapsulates it. You could use node.findPath( endNode ); instead... As a shortcut. Just don't mix-and-match the findPath and Node... ( they'd conflict on the function declaration. )
Reply With Quote