1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
| #define GRID_SIZE 61
#define TS 10
int grid[GRID_SIZE][GRID_SIZE];
// Function Prototypes
void renderGrid();
void setSE();
void makeGrid();
void resetGrid();
enum
{
wallTile,
openTile,
startTile,
endTile,
pathTile,
};
//-------------------------------------- Class Declaration and Instantiation
class Astar
{
public:
// Public Member Variables
enum
{
SEARCHING,
SUCCEEDED,
FAILED,
};
// Node class (class that has x, y, heuristic and parent pointer values
class Node
{
public:
Node()
{
parent = NULL;
g = 0.0;
h = 0.0;
f = 0.0;
}
/*****getDistanceEstimate()*****
*TAKES: int endx: x value of the endNode
* int endy: y value of the endNode
*RETURNS: float: the value of the distance equation squared
*PURPOSE: to calculate and return the distance from this
*node to the endNode
********************************/
float getDistanceEstimate( int endx, int endy )
{
float dx = (float)( (float)x - (float)endx );
float dy = (float)( (float)y - (float)endy );
return ((dx*dx) + (dy*dy));
}
/*****isSameState()*****
*TAKES: Node *rhs: node to check x,y values
*RETURNS: bool: is this the same state?
*PURPOSE: true if the passed node has the same
*x and y values as this node
************************/
bool isSameState( Node *rhs )
{
if( x == rhs -> x && y == rhs -> y )
return true;
else
return false;
}
Node *parent;
float g; // cost of this node + its parents
float h; // heuristic estimate
float f; // g + h
int x, y;
int type;
};
class HeapComparison
{
public:
/*****operator()*****
*TAKES: Node *x: first node for comparison
* Node *y: second node for comparison
*RETURNS: bool: does x have higher f than y?
*PURPOSE: this function is passed to the list sorting
*functions, pop_heap, push_heap, and sort_heap
*this function dictates the order of the list
*the heap functions are an A* optimization
*********************/
bool operator() ( const Node *x, const Node *y ) const
{
return x->f > y->f;
}
};
//---------------------------------------------------------- Member Functions
Astar() { // Constructor
}
~Astar() { // Destructor
clearLists();
}
//Reset function
void clearLists()
{
OPEN.clear();
CLOSED.clear();
SUCCESSORS.clear();
}
/*****getCoords()*****
*TAKES: int xCoord: x coordinate for the desired grid value
* int yCoord: y coordinate for the desired grid value
*RETURNS: int: the tile value of grid[x][y]
*PURPOSE: to return the tile value at coordinates xCoord, yCoord
*Values that are out of bounds (bigger than size of grid)
************************/
int getCoords( int xCoord, int yCoord )
{
if( xCoord < 0 || xCoord >= GRID_SIZE ||
yCoord < 0 || yCoord >= GRID_SIZE )
return wallTile;
return grid[xCoord][yCoord];
}
/*****setStartEnd()*****
*TAKES: int x: x value of startNode
* int y: y value of startNode
* int q: x value of endNode
* int r: y value of endNode
*RETURNS: nothing
*PURPOSE: initializes the startNode and endNode
************************/
void setStartEnd( int x, int y, int q, int r)
{
startNode = new Node;
endNode = new Node;
//Initialize the start and ending nodes
startNode -> x = x;
startNode -> y = y;
startNode -> type = startTile;
endNode -> x = q;
endNode -> y = r;
endNode -> type = endTile;
//Set state of the search algorithm
currentState = SEARCHING;
//Initialize the heuristic variables for the start state
startNode->g = 0;
startNode->h =
startNode->getDistanceEstimate( endNode -> x, endNode ->y );
startNode->f =
startNode->g + startNode->h;
//Starting node has no parents
startNode->parent = NULL;
//Push starting node onto OPEN list
OPEN.push_back( startNode );
// Sort elements in heap
push_heap( OPEN.begin(), OPEN.end(), HeapComparison() );
// Initialise counter for search steps
stepCounter = 0;
}
/*****Search()*****
*TAKES: nothing
*RETURNS: unsigned int: corresponds to a particular state
* SUCCEEDED: found the endNode
* FAILED: didn't find the endNode
* SEARCHING: still searching, keep calling trying
*PURPOSE: A* algorithm. Starts at the lowest f valued node on
*the OPEN list (first iteration is always the startNode) and
*stores it as thisNode. The OPEN list contains every node that
*hasn't been expanded, ie. has not had successors generated for
*it The CLOSED list contains every node that has been expanded,
*Search() then generates all the 0 to 8 successors of thisNode
*and iterates through them. Any successor that is found to meet
*both of the following conditions is placed in the OPEN list
*and it's parent node is stored.
* 1) If this successor is already a node on the OPEN list, and
* the 'f' value of the node on the OPEN list is higher
* than that of the successor. Consequentially, this
* successor was reached faster (from a different direction)
* than it was when it was first put on the OPEN list.
* This successor must be updated on the OPEN list with
* the lower 'f' value.
* 2) If this successor is already a node on the CLOSED list, and
* the 'f' value of the node on the CLOSED list is higher
* than that of the successor. Consequentially, this
* successor was reached faster (from a different direction)
* than it was when it was first put on the CLOSED list.
* Because this successor has already been expanded (it
* is on the CLOSED list) and has a lower 'f' value
* than its similar state on the CLOSED list, this
* successor must be removed from the CLOSED list.
* If this successor meets both criteria, it will be
* placed on the OPEN list and expanded again.
*If this successor is neither on the OPEN nor on the CLOSED lists, it
*will be put on the OPEN list and have it's parent node stored. After
*Search() has stored every worthwhile successor (those that have met
*the two criteria), it will move the successors' parent onto the CLOSED
*list. Search should then be called again, where it will expand the Node
*on the OPEN list with the lowest 'f' value. If a node taken off the OPEN
*list is the endNode, Search() will set the currentState flag to SUCCEEDED
*and terminate the subroutine. If the OPEN list is empty, there are no
*more states to expand, and therefore no way to get to the endNode.
*******************/
unsigned int Search()
{
//Check to see if the search succeeded or failed
if( ( currentState == SUCCEEDED) || ( currentState == FAILED ) )
return currentState;
//The search fails if the OPEN list is empty (no more states to search)
if( OPEN.empty() )
{
currentState = FAILED;
return currentState;
}
// Incremement stepCounter
stepCounter ++;
//Get the node with the lowest f value (list is always sorted in order
//of f values)
Node *thisNode = OPEN.front();
pop_heap( OPEN.begin(), OPEN.end(), HeapComparison() );
OPEN.pop_back();
// Check for the end state
if( thisNode -> type == endTile )
{
//Store the parent of end node so we can move back up the tree
endNode->parent = thisNode->parent;
//Make sure startNode isn't equal to endNode
if( thisNode != startNode )
{
//delete thisNode;
delete thisNode;
}
currentState = SUCCEEDED;
return currentState;
}
//End state not found
else
{
//Generate successors for the node in question
//Start by clearing the successor list of the last "thisNode"
SUCCESSORS.clear();
//Push successors of thisNode into SUCCESSORS list.
Node * newNode;
//Store x and y coords of thisNode's parent so it doesn't go backwards
//Make a case for the startNode (it has no parent)
int parentX = -1;
int parentY = -1;
//Check to see that thisNode has a parent (ie, its not the start node)
if( thisNode -> parent )
{
parentX = thisNode -> parent -> x;
parentY = thisNode -> parent -> y;
}
//Create successor by scanning around thisNode's x,y coords
//Case: Left of thisNode
if( (getCoords( (thisNode -> x)-1, (thisNode -> y) ) != wallTile)
&& !((parentX == (thisNode -> x)-1) && (parentY == (thisNode -> y)))
)
{
newNode = new Node;
newNode -> x = (thisNode -> x)-1;
newNode -> y = thisNode -> y;
newNode -> type = getCoords( (thisNode -> x)-1, (thisNode -> y) );
SUCCESSORS.push_back( newNode );
}
//Case: Right of thisNode
if( (getCoords( (thisNode -> x)+1, (thisNode -> y) ) != wallTile)
&& !((parentX == (thisNode -> x)+1) && (parentY == (thisNode -> y)))
)
{
newNode = new Node;
newNode -> x = (thisNode -> x)+1;
newNode -> y = thisNode -> y;
newNode -> type = getCoords( (thisNode -> x)+1, (thisNode -> y) );
SUCCESSORS.push_back( newNode );
}
//Case: Upper Left of thisNode
if( (getCoords( (thisNode -> x)-1, (thisNode -> y)-1 ) != wallTile)
&& !((parentX == (thisNode -> x)-1) && (parentY == (thisNode -> y)-1))
)
{
newNode = new Node;
newNode -> x = (thisNode -> x)-1;
newNode -> y = (thisNode -> y)-1;
newNode -> type = getCoords( (thisNode -> x)-1, (thisNode -> y)-1 );
SUCCESSORS.push_back( newNode );
}
//Case: Above thisNode
if( (getCoords( (thisNode -> x), (thisNode -> y)-1 ) != wallTile)
&& !((parentX == (thisNode -> x)) && (parentY == (thisNode -> y)-1))
)
{
newNode = new Node;
newNode -> x = thisNode -> x;
newNode -> y = (thisNode -> y)-1;
newNode -> type = getCoords( (thisNode -> x), (thisNode -> y)-1 );
SUCCESSORS.push_back( newNode );
}
//Case: Upper Right of thisNode
if( (getCoords( (thisNode -> x)+1, (thisNode -> y)-1 ) != wallTile)
&& !((parentX == (thisNode -> x)+1)
&& (parentY == (thisNode -> y)-1))
)
{
newNode = new Node;
newNode -> x = (thisNode -> x)+1;
newNode -> y = (thisNode -> y)-1;
newNode -> type =
getCoords( (thisNode -> x)+1, (thisNode -> y)-1 );
SUCCESSORS.push_back( newNode );
}
//Case: Lower Left of thisNode
if( (getCoords( (thisNode -> x)-1, (thisNode -> y)+1 ) != wallTile)
&& !((parentX == (thisNode -> x)-1) && (parentY == (thisNode -> y)+1))
)
{
newNode = new Node;
newNode -> x = (thisNode -> x)-1;
newNode -> y = (thisNode -> y)+1;
newNode -> type = getCoords
( (thisNode -> x)-1, (thisNode -> y)+1 );
SUCCESSORS.push_back( newNode );
}
//Case: Below thisNode
if( (getCoords( (thisNode -> x), (thisNode -> y)+1 ) != wallTile)
&& !((parentX == (thisNode -> x)) && (parentY == (thisNode -> y)+1))
)
{
newNode = new Node;
newNode -> x = thisNode -> x;
newNode -> y = (thisNode -> y)+1;
newNode -> type = getCoords( (thisNode -> x), (thisNode -> y)+1 );
SUCCESSORS.push_back( newNode );
}
//Case: Lower Right of thisNode
if( (getCoords( (thisNode -> x)+1, (thisNode -> y)+1 ) != wallTile)
&& !((parentX == (thisNode -> x)+1)
&& (parentY == (thisNode -> y)+1))
)
{
newNode = new Node;
newNode -> x = (thisNode -> x)+1;
newNode -> y = (thisNode -> y)+1;
newNode -> type = getCoords( (thisNode -> x)+1, (thisNode -> y)+1 );
SUCCESSORS.push_back( newNode );
}
//Iterate through all the successors of thisNode
for( vector< Node * >::iterator successor = SUCCESSORS.begin();
successor != SUCCESSORS.end(); successor ++ )
{
//Store the g value for this successor in a temporary variable
float newg = thisNode->g + 1.0;
//Check to see if this successor is on the open or closed lists
vector< Node * >::iterator openlist;
for( openlist = OPEN.begin(); openlist != OPEN.end(); openlist ++ )
{
if( (*openlist)->isSameState( (*successor) ) )
{
break;
}
}
if( openlist != OPEN.end() )
{
//This successor state is on the OPEN list
//Now check to see which has the lower g value
if( (*openlist) -> g <= newg )
{
delete (*successor);
//the one on OPEN is cheaper than this one
//so trash this successor and continue
continue;
}
}
vector< Node * >::iterator closedlist;
for( closedlist = CLOSED.begin();
closedlist != CLOSED.end(); closedlist ++ )
{
if( (*closedlist) -> isSameState( (*successor) ) )
{
break;
}
}
if( closedlist != CLOSED.end() )
{
//This successor state is on the OPEN list
//Now check to see which has the lower g value
if( (*closedlist) -> g <= newg )
{
//the one on CLOSED is cheaper than this one
//so trash this successor and continue
delete (*successor);
continue;
}
}
//This successor is fewer steps (g's value) away from the start
//Than any occurance on the open or closed list
//save parent so we can back track once (if?) we reach the end
(*successor) -> parent = thisNode;
//Store our temporary g value
(*successor)->g = newg;
//find the distance (squared) from this point to the endnode
(*successor)->h = (*successor) ->
getDistanceEstimate( endNode -> x, endNode -> y );
//Get the final heuristic value f
(*successor)->f = (*successor) -> g + (*successor) -> h;
//Remove successor from CLOSED if it was on it and had lower g
if( closedlist != CLOSED.end() )
{
//remove this successor from CLOSED so we don't
//try to compare it again the next time around
delete (*closedlist);
CLOSED.erase( closedlist );
}
//Update old version of this successor node on OPEN list
if( openlist != OPEN.end() )
{
delete (*openlist);
OPEN.erase( openlist );
//resort the heap
sort_heap( OPEN.begin(), OPEN.end(), HeapComparison() );
}
//Put this successor (with newest values) into the OPEN list
OPEN.push_back( (*successor) );
//Sort the OPEN list
push_heap( OPEN.begin(), OPEN.end(), HeapComparison() );
}
//Push thisNode onto CLOSED, it has been expanded
CLOSED.push_back( thisNode );
}
//End of the else,
//the currentState should only be unsuccessful at this point
return currentState;
}
//Function that moves from the endNode to the startNode
//and changes the path From '.' to 'X'
void writePathToGrid()
{
if( currentState == SUCCEEDED )
{
//Iterate back to the startNode from the endNode
Node *nodeChild = endNode;
Node *nodeParent = endNode->parent;
do
{
if( nodeParent != startNode )
{
nodeParent -> type = pathTile;
grid[nodeParent->x][nodeParent->y] = pathTile;
}
nodeChild = nodeParent;
nodeParent = nodeParent->parent;
}
while( nodeChild != startNode );
}
return;
}
private:
//OPEN list explained in comments before Search()
vector<Node *> OPEN;
//CLOSED list explained in comments before Search()
vector<Node *> CLOSED;
//SUCCESSORS is a list of successive nodes branching out from
//any particular node. It is generated almost every iteration of SEARCH
vector<Node *> SUCCESSORS;
unsigned int currentState;
int stepCounter;
//Start and end state pointers
Node *startNode;
Node *endNode;
} aStarSearch; |