思路:先在神经猫所在位置的六个逃跑方向寻找通路(左、左上、右上、左下、右下、右),再在通路里找到最短路径作为神经猫的逃跑方向,若六个方向都没有通路,则随机选择一个方向移动。
代码实现(注:需要在类中声明字段Hashtable escDir = new Hashtable(); //存放往各个方向逃跑的步数)
/// <summary>
/// 神经猫逃跑方向
/// </summary>
/// <param name="pot">格子信息</param>
/// <param name="x">神经猫所在格子对应二维数组下标的x值</param>
/// <param name="y">神经猫所在格子对应二维数组下标的y值</param>
/// <param name="direction">神经猫移动方向</param>
public void EscDir(Pot[,] pot, int x, int y, out EscapeDirection direction)
{
int min = int.MaxValue; //逃跑的最少步数
EscapeDirection tempDir = EscapeDirection.CATCH; //临时存储逃跑方向
//朝左上方逃跑(局部方法)
void LeftUp()
{
int stepDir = 0; //逃跑步数
for (int i = x, j = y; i > 0 && j > 0;)
{
j = (i + 1) % 2 != 0 ? j : j - 1;
i = i - 1;
if (pot[i, j].PotStu == PotStatus.PASSABLE)
{
stepDir++;
}
else
{
//该逃跑方向上遍历到被阻塞的点,证明该方向没有通路,则把逃跑步数记录为int.MaxValue
escDir.Add(EscapeDirection.TOPLEFT, int.MaxValue);
return;
}
}
escDir.Add(EscapeDirection.TOPLEFT, stepDir);
}
//朝右上方逃跑(局部方法)
void RightUp()
{
int stepDir = 0; //逃跑步数
for (int i = x, j = y; i > 0 && j < pot.GetLength(1) - 1;)
{
j = (i + 1) % 2 != 0 ? j + 1 : j;
i = i - 1;
if (pot[i, j].PotStu == PotStatus.PASSABLE)
{
stepDir++;
}
else
{
escDir.Add(EscapeDirection.TOPRIGHT, int.MaxValue);
return;
}
}
escDir.Add(EscapeDirection.TOPRIGHT, stepDir);
}
//朝左下方逃跑(局部方法)
void LeftDown()
{
int stepDir = 0; //逃跑步数
for (int i = x, j = y; i < pot.GetLength(0) - 1 && j > 0;)
{
j = (i + 1) % 2 != 0 ? j : j - 1;
i = i + 1;
if (pot[i, j].PotStu == PotStatus.PASSABLE)
{
stepDir++;
}
else
{
escDir.Add(EscapeDirection.LEFTDOWN, int.MaxValue);
return;
}
}
escDir.Add(EscapeDirection.LEFTDOWN, stepDir);
}
//朝右下方逃跑(局部方法)
void RightDown()
{
int stepDir = 0; //逃跑步数
for (int i = x, j = y; i < pot.GetLength(0) - 1 && j < pot.GetLength(1) - 1;)
{
j = (i + 1) % 2 != 0 ? j + 1 : j;
i = i + 1;
if (pot[i, j].PotStu == PotStatus.PASSABLE)
{
stepDir++;
}
else
{
escDir.Add(EscapeDirection.RIGHTDOWN, int.MaxValue);
return;
}
}
escDir.Add(EscapeDirection.RIGHTDOWN, stepDir);
}
//朝左方逃跑(局部方法)
void Left()
{
int stepDir = 0; //逃跑步数
for (int i = x, j = y; j > 0;)
{
j = j - 1;
if (pot[i, j].PotStu == PotStatus.PASSABLE)
{
stepDir++;
}
else
{
escDir.Add(EscapeDirection.LEFT, int.MaxValue);
return;
}
}
escDir.Add(EscapeDirection.LEFT, stepDir);
}
//朝右方逃跑(局部方法)
void Right()
{
int stepDir = 0; //逃跑步数
for (int i = x, j = y; j < pot.GetLength(1) - 1;)
{
j = j + 1;
if (pot[i, j].PotStu == PotStatus.PASSABLE)
{
stepDir++;
}
else
{
escDir.Add(EscapeDirection.RIGHT, int.MaxValue);
return;
}
}
escDir.Add(EscapeDirection.RIGHT, stepDir);
}
LeftDown();
Left();
LeftUp();
RightUp();
Right();
RightDown();
//遍历哈希表,找到逃跑的最少步数
foreach (DictionaryEntry entry in escDir)
{
if ((int)entry.Value < min)
{
min = (int)entry.Value;
tempDir = (EscapeDirection)entry.Key;
}
}
direction = tempDir;
escDir.Clear();
}