-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpathfinder.cpp
683 lines (551 loc) · 20.3 KB
/
pathfinder.cpp
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
using namespace std;
#include "pathfinder.h"
bool compare(Node* lhs, Node* rhs)
{
return (lhs->getTotalCost() > rhs->getTotalCost());
}
Pathfinder::Pathfinder(Snake* snake) : snake(snake), numRows(snake->h() / 20),
numCols(snake->w() / 20), pathFound(false)
{
for (int i = 0; i < numRows; i++)
{
vector<Node*> currentRow;
for (int j = 0; j < numCols; j++)
{
Node* tempNode = new Node(j, i);
snake->add(tempNode); //make nodes visible in the window
currentRow.push_back(tempNode);
}
gameState.push_back(currentRow);
}
}
void Pathfinder::resetPathFlag()
{
this->pathFound = false;
}
void Pathfinder::AStar(int startX, int startY, int goalX, int goalY)
{
clock_t startTime = clock();
cout << "AStar: starting search from (" << startX << ", " << startY << ") to ("
<< goalX << ", " << goalY << ")" << endl;
//fetch the most recent iteration of the game board
vector<vector<Node*>> currGameState = updateGameState();
//initialize the open and closed sets
vector<Node*> openSet;
vector<Node*> closedSet;
//init start node and add to open set
openSet.push_back(currGameState.at(startY).at(startX));
currGameState.at(startY).at(startX)->setMoveCost(0);
currGameState.at(startY).at(startX)->
setTotalCost(currGameState.at(startY).at(startX)->heuristic(goalX, goalY));
while(!openSet.empty())
{
//choose the node in the open set w/ the lowest total cost
sort(openSet.begin(), openSet.end(), compare);
Node* current = openSet.back();
//don't do anymore pathfinding if we've found the goal!
if (checkGoal(current->getY(), current->getX(), goalY, goalX))
{
clock_t finishTime = clock();
cout << "AStar: goal node found! (nodes explored = "
<< openSet.size() + closedSet.size() << ")" << endl;
double searchTime = (double)((finishTime-startTime)*1000/(double)CLOCKS_PER_SEC);
timeStats.push_back(searchTime);
cout << "AStar: time taken = " << searchTime << " ms "<< endl;
nodeStats.push_back(openSet.size() + closedSet.size());
currGameState.at(startY).at(startX)->setParent(nullptr); //shitty spaghet code
//draw the open and closed sets
cout << "AStar: drawing open set (cyan) ... ";
drawSet(openSet, FL_CYAN);
cout << "done" << endl;
cout << "AStar: drawing closed set (blue) ... ";
drawSet(closedSet, FL_BLUE);
cout << "done" << endl;
//~ currGameState.at(startY).at(startX)->color(FL_MAGENTA);
//write path directly to snake's input buffer
cout << "AStar: writing path to input buffer ... ";
snake->buffer = buildPath(currGameState, currGameState.at(goalY).at(goalX));
cout << "done" << endl;
cout << "------------------------------" << endl;
//tell the game to stop pathfinding (we're done until we eat the food)
pathFound = true;
return;
}
//add the current node to the closed set and remove from open set
openSet.pop_back();
closedSet.push_back(current);
//fetch the four adjacent nodes to the current node (if they are valid)
vector<Node*> neighborVec = getNeighbors2(currGameState, current);
for (int i = 0; i < neighborVec.size(); i++)
{
Node* currentNeighbor = neighborVec.at(i);
//if neighbor is not in closed set
if (!nodeInSet(closedSet, currentNeighbor))
{
//update score
//~ currentNeighbor->setTotalCost(currentNeighbor->heuristic(goalX, goalY)); //greedy best-first cost (heuristic only)
currentNeighbor->updateTotalCost(goalX, goalY);
//if neighbor is not in open set
if (!nodeInSet(openSet, currentNeighbor))
{
openSet.push_back(currentNeighbor);
}
}
}
}
clock_t finishTime = clock();
pathFound = false; //tell the game to keep pathfinding on each new frame
cout << "AStar: no path found! (nodes explored = " << openSet.size() + closedSet.size()
<< ")" << endl;
double searchTime = (double)((finishTime-startTime)*1000/(double)CLOCKS_PER_SEC);
cout << "AStar: time taken = " << searchTime << " ms "<< endl;
timeStats.push_back(searchTime);
nodeStats.push_back(openSet.size() + closedSet.size());
cout << "AStar: drawing open set (cyan) ... ";
drawSet(openSet, FL_CYAN);
cout << "done" << endl;
cout << "AStar: drawing closed set (blue) ... ";
drawSet(closedSet, FL_BLUE);
cout << "done" << endl;
//~ currGameState.at(startY).at(startX)->color(FL_MAGENTA);
cout << "------------------------------" << endl;
}
void Pathfinder::greedyBFS(int startX, int startY, int goalX, int goalY)
{
clock_t startTime = clock();
cout << "GreedyBFS: starting search from (" << startX << ", " << startY << ") to ("
<< goalX << ", " << goalY << ")" << endl;
//fetch the most recent iteration of the game board
vector<vector<Node*>> currGameState = updateGameState();
//initialize the open and closed sets
vector<Node*> openSet;
vector<Node*> closedSet;
//init start node and add to open set
openSet.push_back(currGameState.at(startY).at(startX));
currGameState.at(startY).at(startX)->setMoveCost(0);
currGameState.at(startY).at(startX)->
setTotalCost(currGameState.at(startY).at(startX)->heuristic(goalX, goalY));
while(!openSet.empty())
{
//choose the node in the open set w/ the lowest total cost
sort(openSet.begin(), openSet.end(), compare);
Node* current = openSet.back();
//don't do anymore pathfinding if we've found the goal!
if (checkGoal(current->getY(), current->getX(), goalY, goalX))
{
clock_t finishTime = clock();
cout << "GreedyBFS: goal node found! (nodes explored = "
<< openSet.size() + closedSet.size() << ")" << endl;
double searchTime = (double)((finishTime-startTime)*1000/(double)CLOCKS_PER_SEC);
cout << "GreedyBFS: time taken = " << searchTime << " ms "<< endl;
timeStats.push_back(searchTime);
nodeStats.push_back(openSet.size() + closedSet.size());
currGameState.at(startY).at(startX)->setParent(nullptr); //shitty spaghet code
//draw the open and closed sets
cout << "GreedyBFS: drawing open set (cyan) ... ";
drawSet(openSet, FL_CYAN);
cout << "done" << endl;
cout << "GreedyBFS: drawing closed set (blue) ... ";
drawSet(closedSet, FL_BLUE);
cout << "done" << endl;
//~ currGameState.at(startY).at(startX)->color(FL_MAGENTA);
//write path directly to snake's input buffer
cout << "GreedyBFS: writing path to input buffer ... ";
snake->buffer = buildPath(currGameState, currGameState.at(goalY).at(goalX));
cout << "done" << endl;
cout << "------------------------------" << endl;
//tell the game to stop pathfinding (we're done until we eat the food)
pathFound = true;
return;
}
//add the current node to the closed set and remove from open set
openSet.pop_back();
closedSet.push_back(current);
//fetch the four adjacent nodes to the current node (if they are valid)
vector<Node*> neighborVec = getNeighbors2(currGameState, current);
for (int i = 0; i < neighborVec.size(); i++)
{
Node* currentNeighbor = neighborVec.at(i);
//if neighbor is not in closed set
if (!nodeInSet(closedSet, currentNeighbor))
{
//update score
currentNeighbor->setTotalCost(currentNeighbor->heuristic(goalX, goalY)); //greedy best-first cost (heuristic only)
//if neighbor is not in open set
if (!nodeInSet(openSet, currentNeighbor))
{
openSet.push_back(currentNeighbor);
}
}
}
}
clock_t finishTime = clock();
pathFound = false; //tell the game to keep pathfinding on each new frame
cout << "GreedyBFS: no path found! (nodes explored = " << openSet.size() + closedSet.size()
<< ")" << endl;
double searchTime = (double)((finishTime-startTime)*1000/(double)CLOCKS_PER_SEC);
cout << "GreedyBFS: time taken = " << searchTime << " ms "<< endl;
timeStats.push_back(searchTime);
nodeStats.push_back(openSet.size() + closedSet.size());
cout << "GreedyBFS: drawing open set (cyan) ... ";
drawSet(openSet, FL_CYAN);
cout << "done" << endl;
cout << "GreedyBFS: drawing closed set (blue) ... ";
drawSet(closedSet, FL_BLUE);
cout << "done" << endl;
cout << "------------------------------" << endl;
}
void Pathfinder::drawSet(vector<Node*> set, Fl_Color color)
{
for (int i = 0; i < set.size(); i++)
{
set.at(i)->color(color);
}
}
void Pathfinder::BFS(int startX, int startY, int goalX, int goalY)
{
clock_t startTime = clock();
cout << "BFS: starting search from (" << startX << ", " << startY << ") to ("
<< goalX << ", " << goalY << ")" << endl;
//fetch the most recent iteration of the game board
vector<vector<Node*>> currGameState = updateGameState();
//initialize the open and closed sets
vector<Node*> openSet;
vector<Node*> closedSet;
//init start node and add to open set
openSet.push_back(currGameState.at(startY).at(startX));
while (!openSet.empty())
{
Node* current = openSet.front();
openSet.erase(openSet.begin());
if (checkGoal(current->getY(), current->getX(), goalY, goalX))
{
clock_t finishTime = clock();
cout << "BFS: goal node found! (nodes explored = "
<< openSet.size() + closedSet.size() << ")" << endl;
double searchTime = (double)((finishTime-startTime)*1000/(double)CLOCKS_PER_SEC);
cout << "BFS: time taken = " << searchTime << " ms "<< endl;
timeStats.push_back(searchTime);
nodeStats.push_back(openSet.size() + closedSet.size());
currGameState.at(startY).at(startX)->setParent(nullptr); //shitty spaghet code
//draw the open and closed sets
cout << "BFS: drawing open set (cyan) ... ";
drawSet(openSet, FL_CYAN);
cout << "done" << endl;
cout << "BFS: drawing closed set (blue) ... ";
drawSet(closedSet, FL_BLUE);
cout << "done" << endl;
//write path directly to snake's input buffer
cout << "BFS: writing path to input buffer ... ";
snake->buffer = buildPath(currGameState, currGameState.at(goalY).at(goalX));
cout << "done" << endl;
cout << "------------------------------" << endl;
//tell the game to stop pathfinding (we're done until we eat the food)
pathFound = true;
return;
}
vector<Node*> neighborVec = getNeighborsBFS(currGameState, current);
for (int i = 0; i <neighborVec.size() ; i++)
{
Node* currentNeighbor = neighborVec.at(i);
if (nodeInSet(closedSet, currentNeighbor))
{
continue;
}
if(!nodeInSet(openSet, currentNeighbor))
{
currentNeighbor->setParent(current);
openSet.push_back(currentNeighbor);
}
}
closedSet.push_back(current);
}
clock_t finishTime = clock();
pathFound = false; //tell the game to keep pathfinding on each new frame
cout << "BFS: no path found! (nodes explored = " << openSet.size() + closedSet.size()
<< ")" << endl;
double searchTime = (double)((finishTime-startTime)*1000/(double)CLOCKS_PER_SEC);
cout << "BFS: time taken = " << searchTime << " ms "<< endl;
timeStats.push_back(searchTime);
nodeStats.push_back(openSet.size() + closedSet.size());
cout << "BFS: drawing open set (cyan) ... ";
drawSet(openSet, FL_CYAN);
cout << "done" << endl;
cout << "BFS: drawing closed set (blue) ... ";
drawSet(closedSet, FL_BLUE);
cout << "done" << endl;
cout << "------------------------------" << endl;
}
void Pathfinder::DFS(int startX, int startY, int goalX, int goalY)
{
clock_t startTime = clock();
cout << "DFS: starting search from (" << startX << ", " << startY << ") to ("
<< goalX << ", " << goalY << ")" << endl;
vector<vector<Node*>> currGameState = updateGameState();
vector<Node*> discoveredSet;
vector<Node*> stack;
stack.push_back(currGameState.at(startY).at(startX));
while (!stack.empty())
{
Node* current = stack.back();
stack.pop_back();
if (checkGoal(current->getY(), current->getX(), goalY, goalX))
{
clock_t finishTime = clock();
cout << "DFS: goal node found! (nodes explored = "
<< discoveredSet.size() << ")" << endl;
double searchTime = (double)((finishTime-startTime)*1000/(double)CLOCKS_PER_SEC);
cout << "DFS: time taken = " << searchTime << " ms "<< endl;
timeStats.push_back(searchTime);
nodeStats.push_back(discoveredSet.size());
currGameState.at(startY).at(startX)->setParent(nullptr); //shitty spaghet code
cout << "DFS: drawing discovered set (blue) ... ";
drawSet(discoveredSet, FL_BLUE);
cout << "done" << endl;
//write path directly to snake's input buffer
cout << "DFS: writing path to input buffer ... ";
snake->buffer = buildPath(currGameState, currGameState.at(goalY).at(goalX));
cout << "done" << endl;
cout << "------------------------------" << endl;
//tell the game to stop pathfinding (we're done until we eat the food)
pathFound = true;
return;
}
if (!nodeInSet(discoveredSet, current))
{
discoveredSet.push_back(current);
vector<Node*>neighborVec = getNeighborsBFS(currGameState, current);
for (int i = 0; i < neighborVec.size(); i++)
{
Node* currentNeighbor = neighborVec.at(i);
stack.push_back(currentNeighbor);
if (currentNeighbor->getParent() == nullptr)
currentNeighbor->setParent(current);
}
}
}
clock_t finishTime = clock();
pathFound = false; //tell the game to keep pathfinding on each new frame
cout << "DFS: no path found! (nodes explored = " << discoveredSet.size()
<< ")" << endl;
double searchTime = (double)((finishTime-startTime)*1000/(double)CLOCKS_PER_SEC);
cout << "DFS: time taken = " << searchTime << " ms "<< endl;
timeStats.push_back(searchTime);
nodeStats.push_back(discoveredSet.size());
cout << "BFS: drawing discovered set (blue) ... ";
drawSet(discoveredSet, FL_BLUE);
cout << "done" << endl;
cout << "------------------------------" << endl;
}
vector<Node*> Pathfinder::getNeighbors2(vector<vector<Node*>> gameState, Node* node)
{
//will contain the VALID adjacent nodes to the argument node
vector<Node*> neighborVec;
int row = node->getY();
int col = node->getX();
/* for each potential neighbor:
* -check if it's in bounds
* -check if it's NOT an obstacle
* -if the potential neighbor does not have a parent, set it to the argument
* node */
if (checkBounds(row - 1, col) && (!checkBlocked(gameState, row - 1, col)))
{
if (gameState.at(row - 1).at(col)->getParent() == nullptr)
{
gameState.at(row - 1).at(col)->setParent(node);
gameState.at(row - 1).at(col)->setMoveCost(node->getMoveCost() + 1);
}
neighborVec.push_back(gameState.at(row - 1).at(col));
}
if (checkBounds(row + 1, col) && (!checkBlocked(gameState, row + 1, col)))
{
if (gameState.at(row + 1).at(col)->getParent() == nullptr)
{
gameState.at(row + 1).at(col)->setParent(node);
gameState.at(row + 1).at(col)->setMoveCost(node->getMoveCost() + 1);
}
neighborVec.push_back(gameState.at(row + 1).at(col));
}
if (checkBounds(row, col - 1) && (!checkBlocked(gameState, row, col - 1)))
{
if (gameState.at(row).at(col - 1)->getParent() == nullptr)
{
gameState.at(row).at(col - 1)->setParent(node);
gameState.at(row).at(col - 1)->setMoveCost(node->getMoveCost() + 1);
}
neighborVec.push_back(gameState.at(row).at(col - 1));
}
if (checkBounds(row, col + 1) && (!checkBlocked(gameState, row, col + 1)))
{
if (gameState.at(row).at(col + 1)->getParent() == nullptr)
{
gameState.at(row).at(col + 1)->setParent(node);
gameState.at(row).at(col + 1)->setMoveCost(node->getMoveCost() + 1);
}
neighborVec.push_back(gameState.at(row).at(col + 1));
}
return neighborVec;
}
vector<Node*> Pathfinder::getNeighborsBFS(vector<vector<Node*>> gameState, Node* node)
{
//will contain the VALID adjacent nodes to the argument node
vector<Node*> neighborVec;
int row = node->getY();
int col = node->getX();
/* for each potential neighbor:
* -check if it's in bounds
* -check if it's NOT an obstacle
*/
if (checkBounds(row - 1, col) && (!checkBlocked(gameState, row - 1, col)))
{
neighborVec.push_back(gameState.at(row - 1).at(col));
}
if (checkBounds(row + 1, col) && (!checkBlocked(gameState, row + 1, col)))
{
neighborVec.push_back(gameState.at(row + 1).at(col));
}
if (checkBounds(row, col - 1) && (!checkBlocked(gameState, row, col - 1)))
{
neighborVec.push_back(gameState.at(row).at(col - 1));
}
if (checkBounds(row, col + 1) && (!checkBlocked(gameState, row, col + 1)))
{
neighborVec.push_back(gameState.at(row).at(col + 1));
}
return neighborVec;
}
vector<string> Pathfinder::buildPath(vector<vector<Node*>> gameState, Node* goal)
{
//Start from goal node, move backwards to start
vector<string> pathBuffer;
Node* current = goal;
int pathLength = 0;
while (current != nullptr)
{
current->color(FL_RED);
Node* currentParent = current->getParent();
if (currentParent == nullptr)
break; //you're dereferencing a null pointer! open your eyes!
int currentX = current->getX();
int currentY = current->getY();
int parentX = currentParent->getX();
int parentY = currentParent->getY();
//parent = closer along path towards goal than current
if (currentX < parentX)
{
pathBuffer.push_back("LEFT");
}
else if (currentX > parentX)
{
pathBuffer.push_back("RIGHT");
}
else if (currentY < parentY)
{
pathBuffer.push_back("UP");
}
else
{
pathBuffer.push_back("DOWN");
}
pathLength++;
//traverse the path by moving to the next successor node
current = currentParent;
}
//add the current entry to the statistics vector
pathStats.push_back(pathLength);
return pathBuffer;
}
void Pathfinder::setSnake(Snake* snake){ this->snake = snake; }
vector<vector<Node*>> Pathfinder::updateGameState()
{
//initialize all grid cells to be empty
//initialize game state vector
for (int i = 0; i < numRows; i++)
{
vector<Node*> currentRow;
for (int j = 0; j < numCols; j++)
{
gameState.at(i).at(j)->reset();
}
}
//set the snake's body as obstacles (ignore the head)
for (int i = 1; i < snake->body.size(); i++)
{
gameState.at(snake->body.at(i)->getY() / 20)
.at(snake->body.at(i)->getX() / 20)->setObstacle(true);
}
return gameState;
}
void Pathfinder::printGameState(vector<vector<Node*>> gameState)
{
cout << endl;
for (int i = 0; i < gameState.size(); i++)
{
for (int j = 0; j < gameState.at(i).size(); j++)
{
if (gameState.at(i).at(j)->checkObstacle())
cout << "1";
else
cout << "0";
}
cout << endl;
}
}
void Pathfinder::printStats()
{
cout << "----------STATS----------" << endl;
cout << "Average nodes explored: " << calcAvg(nodeStats) << " nodes" << endl;
cout << "Average path length: " << calcAvg(pathStats) << " nodes" << endl;
cout << "Average time taken: " << calcAvg(timeStats) << " ms" << endl;
}
bool Pathfinder::nodeInSet(vector<Node*> set, Node* node)
{ //linearly search the argument set for the argument node
for (int i = 0; i < set.size(); i++)
{
if (node == set.at(i))
{
return true;
}
}
return false;
}
void Pathfinder::setRepeatSearch(bool repeat)
{
this->repeatSearch = repeat;
}
bool Pathfinder::checkRepeatSearch()
{
return this->repeatSearch;
}
bool Pathfinder::checkPathFound()
{
return this->pathFound;
}
bool Pathfinder::checkBounds(int row, int col)
{
//check if the cell is within the board
if (col < 0 || col > numCols - 1 || row < 0 || row > numRows - 1)
return false;
else
return true;
}
bool Pathfinder::checkGoal(int row, int col, int goalRow, int goalCol)
{
return ((row == goalRow) && (col == goalCol));
}
bool Pathfinder::checkBlocked(vector<vector<Node*>> gameState, int row, int col)
{
return gameState.at(row).at(col)->checkObstacle();
}
double Pathfinder::calcAvg(vector<double> data)
{
double dataSum = accumulate(data.begin(), data.end(), 0.0);
double mean = dataSum / (double) data.size();
return mean;
}
double Pathfinder::calcAvg(vector<int> data)
{
int dataSum = accumulate(data.begin(), data.end(), 0);
double mean = (double) dataSum / (double) data.size();
return mean;
}