【发布时间】:2017-10-23 00:36:37
【问题描述】:
我正在尝试为游戏创建寻路算法。基本上,在玩家掷出一个数字后,我需要确定玩家最终可能出现在网格上的所有可能位置。玩家在给定一步后不能直接向后移动,并且玩家每一步只能移动一个格子。
问题是,现在我正试图通过沿图表递归导航并手动检查每个有效动作来强制解决方案。
伪代码:
// Recursive function for navigating one step at a time.
function navigate($stamina, $coords, $coords_previous)
{
// If the movement stamina has not been spent.
if ($stamina != 0)
{
// Note: there may be less than four neighboring
// cells in a given location due to obstacles.
foreach ($neighboring_cells as $coords_neighboring)
{
// If the coordinates of the neighbor are not the same as the
// coordinates of the previous move (we can't move backwards)
if ($coords_neighboring != $coords_previous)
{
$stamina--;
// Recurse.
navigate($stamina, $coords_neighboring, $coords);
}
}
}
else
{
// No more stamina.
// Add $coords to our array of endpoints.
}
}
这适用于小卷(低$stamina 值)。然而,随着$stamina 的增加,这种方法开始变得超级多余。这是因为玩家可以一遍又一遍地绕圈移动,从而成倍增加潜在端点的数量。
我的问题是,可以做些什么来减少上述函数的冗余?
【问题讨论】:
-
玩家可以提前停止吗?
-
不行,玩家只能移动掷出的数字。然而,同样,玩家可以绕圈移动,所以如果玩家掷出 5 并移动
up->right->down->left->left,就好像玩家只向左移动了一个格子。