您可以使用 减少嵌套 if 的数量continue
。一般来说,以下两个代码块是等价的:
while(conditionA){
if(conditionB){
doStuff();
}
}
while(conditionA){
if (!conditionB){continue;}
doStuff();
}
我们可以使用这个原则来减少代码中嵌套 if 的数量。
void AStarImpl::FindAdjacent(Node* pNode)
{
for (int i = -1; i <= 1; i++)
{
for (int j = -1; j <= 1; j++)
{
if (pNode->mX == Map::GetInstance()->mMap[pNode->mX + i][pNode->mY + j].mX && pNode->mY == Map::GetInstance()->mMap[pNode->mX + i][pNode->mY + j].mY){continue;}
if (pNode->mX + i > 14 || pNode->mY + j > 14){continue;}
if (pNode->mX + i < 0 || pNode->mY + j < 0){continue;}
if (Map::GetInstance()->mMap[pNode->mX + i][pNode->mY + j].mTypeID == NODE_TYPE_SOLID){continue;}
if (find(mOpenList.begin(), mOpenList.end(), &Map::GetInstance()->mMap[pNode->mX + i][pNode->mY + j]) != mOpenList.end()){continue;}
Map::GetInstance()->mMap[pNode->mX+i][pNode->mY+j].mParent = &Map::GetInstance()->mMap[pNode->mX][pNode->mY];
mOpenList.push_back(&Map::GetInstance()->mMap[pNode->mX+i][pNode->mY+j]);
}
}
mClosedList.push_back(&Map::GetInstance()->mMap[pNode->mX][pNode->mY]);
}
如果我正确理解您的第一个if
条件,您只是试图断言 pNode 不是它自己的邻居。在这种情况下,您可以将代码更改为:
void AStarImpl::FindAdjacent(Node* pNode)
{
for (int i = -1; i <= 1; i++)
{
for (int j = -1; j <= 1; j++)
{
if (i == 0 && j == 0){continue;}
if (pNode->mX + i > 14 || pNode->mY + j > 14){continue;}
if (pNode->mX + i < 0 || pNode->mY + j < 0){continue;}
if (Map::GetInstance()->mMap[pNode->mX + i][pNode->mY + j].mTypeID == NODE_TYPE_SOLID){continue;}
if (find(mOpenList.begin(), mOpenList.end(), &Map::GetInstance()->mMap[pNode->mX + i][pNode->mY + j]) != mOpenList.end()){continue;}
Map::GetInstance()->mMap[pNode->mX+i][pNode->mY+j].mParent = &Map::GetInstance()->mMap[pNode->mX][pNode->mY];
mOpenList.push_back(&Map::GetInstance()->mMap[pNode->mX+i][pNode->mY+j]);
}
}
mClosedList.push_back(&Map::GetInstance()->mMap[pNode->mX][pNode->mY]);
}
理想情况下,您的 FindAdjacent 方法根本不需要修改开放集或封闭集。相反,让它返回所有邻居,无论它们是打开还是关闭。如果您想将这些邻居添加到打开或关闭的集合中,或者检查它们是否是这些集合的成员,则应该在实际实现 aStar 算法的方法中完成。
Vector<Node> AStarImpl:FindAdjacent(Node* pNode)
{
Vector<Node> neighbors;
for (int i = -1; i <= 1; i++)
{
for (int j = -1; j <= 1; j++)
{
if (i == 0 && j == 0){continue;}
if (pNode->mX + i > 14 || pNode->mY + j > 14){continue;}
if (pNode->mX + i < 0 || pNode->mY + j < 0){continue;}
if (Map::GetInstance()->mMap[pNode->mX + i][pNode->mY + j].mTypeID == NODE_TYPE_SOLID){continue;}
neighbors.push_back(Map::GetInstance()->mMap[pNode->mX+i][pNode->mY+j]);
}
}
return neighbors;
}
您多次执行某些相同的操作。您可以通过将这些操作的结果存储在变量中来使您的意图更加清晰。这样做不会使您的代码更短,但可能会使其更具可读性。
Vector<Node> AStarImpl:FindAdjacent(Node* pNode)
{
Vector<Node> neighbors;
for (int i = -1; i <= 1; i++)
{
for (int j = -1; j <= 1; j++)
{
if (i == 0 && j == 0){continue;}
int x = pNode->mX + i;
int y = pNode->mY + j;
if (x > 14 || y > 14){continue;}
if (x < 0 || y < 0){continue;}
Node candidate = Map::GetInstance()->mMap[x][y];
if (candidate.mTypeID == NODE_TYPE_SOLID){continue;}
neighbors.push_back(candidate);
}
}
return neighbors;
}