朋友参加个面试,面试官问的问题:
就是战旗游戏能走多远的问题,有初始的行动力,不同地形会消耗不同的行动力,然后都能走到那些位置~
刚听到问题的时候,感觉应该是A*的思路来解答,结果是想复杂了,实际比A*还要简单~
做个Demo试试吧~~~~
思路就是从中心点,一圈一圈向外遍历,一直遍历到行动力没了为止。
我这里是用递归做的,核心代码贴在下面。
//初始点
void StartAt(int x, int y, int rest)
{
if (Nodes.Count > y)
{
if (Nodes[y].Count > x)
{
var n = Nodes[y][x];
n.SetColor(Color.red);
n.rest = rest;
}
}
l.Clear();
l.Add(Nodes[y][x]);
GoNextStep();
}
List<Node> tmp = new List<Node>();
//向外遍历
void GoNextStep()
{
tmp.Clear();
foreach (var item in l)
{
int xx = 0;
int yy = 0;
Debug.Log("-------------------");
xx = item.x - 1;
yy = item.y;
CheckNode(xx, yy, item.rest);
xx = item.x + 1;
yy = item.y;
CheckNode(xx, yy, item.rest);
xx = item.x;
yy = item.y + 1;
CheckNode(xx, yy, item.rest);
xx = item.x;
yy = item.y - 1;
CheckNode(xx, yy, item.rest);
}
l.Clear();
if (tmp.Count > 0)
{
Debug.LogError("tmp.Count " + tmp.Count);
l.AddRange(tmp);
GoNextStep();
}
}
//检测四周的方块能否继续拓展,同时比较剩余行动力,如果剩余行动力更高,则加入下轮遍历的容器中
private void CheckNode(int xx, int yy, int rest)
{
Debug.Log("check x : " + xx + ", y : " + yy);
if (Nodes.Count > yy && yy >= 0)
{
if (Nodes[yy].Count > xx && xx >= 0)
{
var n = Nodes[yy][xx];
int newRest = rest - n.cost;
if (newRest > n.rest)
{
n.rest = newRest;
if (n.rest > 0)
{
n.SetColor(Color.green);
tmp.Add(n);
}
else
{
n.SetColor(Color.red);
}
}
}
}
}
还是很简单的~
效果如下:


别说~ 做出来还是挺有成就感 挺好玩儿的~ (其实俺特喜欢战棋类游戏~ )
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
项目传上来:https://github.com/PatrickBoomBoom/CheckHowFarCanGo.git
&spm=1001.2101.3001.5002&articleId=107668908&d=1&t=3&u=2a59998c91834b38adfba3a3042d7722)
7400

被折叠的 条评论
为什么被折叠?



