Skip to content

Instantly share code, notes, and snippets.

@ChunkinFlubber
Created March 13, 2017 23:53
Show Gist options
  • Save ChunkinFlubber/313b4d72d8dbe7e65f378bd8d168ed6c to your computer and use it in GitHub Desktop.
Save ChunkinFlubber/313b4d72d8dbe7e65f378bd8d168ed6c to your computer and use it in GitHub Desktop.
This is one of my code snippets for review by employers. This Specific code snippet is for an A* algorithm to find a path through a 2d grid.
///////////////////////////////////////////////
// A* path search through a 2d grid of tiles
///////////////////////////////////////////////
void PathSearch::enter(int startRow, int startColumn, int goalRow, int goalColumn)
{
Goal = NodeMap[tilemap->getTile(goalRow, goalColumn)];
node = new PlannerNode;
node->vertex = NodeMap[tilemap->getTile(startRow, startColumn)];
node->parent = nullptr;
node->heuristicCost = estimate(node->vertex, Goal);
node->givenCost = 0;
node->finalCost = node->givenCost + node->heuristicCost * hWeight;
VisitedMap[node->vertex] = node;
open.push(node);
}
void PathSearch::update(long timeslice)
{
while (!open.empty())
{
node = open.front();
open.pop();
//Is it the Goal?
if (node->vertex == Goal)
{
PrevNode = node;
while (PrevNode != nullptr)
{
endpath.push_back(PrevNode->vertex->tile);
PrevNode = PrevNode->parent;
}
}
//Get its children/edges and add them to the queue
for (int i = node->vertex->edges.size() - 1; i >= 0 ; --i)
{
suc = NodeMap[node->vertex->edges[i]];
tempNode = VisitedMap[suc];
tempGivenCost = node->givenCost + node->vertex->edges[i]->getWeight();
if (tempNode)
{
if (tempGivenCost < tempNode->givenCost)
{
open.remove(tempNode);
tempNode->givenCost = tempGivenCost;
tempNode->finalCost = tempNode->givenCost + tempNode->heuristicCost * hWeight;
tempNode->parent = node;
open.push(tempNode);
}
}
else
{
Newnode = PlannerNodeContainer.Get();
Newnode->parent = node;
Newnode->vertex = suc;
Newnode->heuristicCost = estimate(Newnode->vertex, Goal);
Newnode->givenCost = tempGivenCost;
Newnode->finalCost = tempGivenCost + Newnode->heuristicCost * hWeight;
VisitedMap[suc] = Newnode;
open.push(Newnode);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment