public class Utilities
{
///
/// 洗牌算法,
///
/// 随机重排的数组
///
public static Coord[] ShuffleCoords(Coord[] dateArray)
{
for (int i = 0; i < dateArray.Length; i++)
{
//将每次随机到的元素放到首位,第二次随机从“队首+1~最后元素”开始随机,这样每次随机到的即不为同一元素
int random = Random.Range(i, dateArray.Length);
//SWAP
Coord temp = dateArray[random];
dateArray[random] = dateArray[i];
dateArray[i] = temp;
}
return dateArray;
}
}
//应用程序
shuffleCoords = new Queue
public Coord GetRandomCoord()
{
Coord randomCoord = shuffleCoords.Dequeue();
shuffleCoords.Enqueue(randomCoord);
return randomCoord;
}
——————————————————————————————————————————————————
///
/// 洪水填充算法
///
/// 地图上的位置是否存在障碍物
/// 应该时候能承担障碍物数量
///
public bool MapIsFullyAccessible(bool[,] _mapObstacles, int _currentObsCount)
{
bool[,] mapFlag = new bool[_mapObstacles.GetLength(0), _mapObstacles.GetLength(1)];
Queue
queue.Enqueue(mapCenter);
mapFlag[mapCenter.x, mapCenter.y] = true;//中心点标记为已检测
int accessibleCount = 1;//可以行走的格子数量
while(queue.Count>0)
{
Coord currentTile = queue.Dequeue();
for (int x = -1; x <=1; x++)
{
for (int y = -1; y <=1; y++)
{
int neighborX = currentTile.x + x;
int neighborY = currentTile.y + y;
if (x==0||y==0)//检测上下左右四个相邻的位置是否可行
{
if(neighborX >=0&&neighborX<_mapObstacles.GetLength(0)
&& neighborY>=0&&neighborY<_mapObstacles.GetLength(1))//范围限定在地图范围内
{
//该位置未检测,且不存在障碍物时
if(!mapFlag[neighborX,neighborY]&&!_mapObstacles[neighborX,neighborY])
{
mapFlag[neighborX, neighborY] = true;
accessibleCount++;
queue.Enqueue(new Coord(neighborX, neighborY));
}
}
}
}
}
}
int walkableCount = (int)(mapSize.x * mapSize.y - _currentObsCount);//地图上应该可行走位置的数量
return accessibleCount == walkableCount;//联通路径总的可行走数量与目标值相同时则可依据_mapObstacles中位置生成障碍物
}
------------------------重置内置运算符“operator”--------------------------
**C#支持的运算符重载**
可重载的一元运算符 (overloadable unary operator) 有:
-
- ! ~ ++ -- true false
可重载的二元运算符 (overloadable binary operator) 有:
- ! ~ ++ -- true false
-
-
- / % & | ^ << >> == != > < >= <=
struct Human
{
public int s1;
public int s2;
public Human(int a, int b)
{
s1 = a;
s2 = b;
}
public static Human operator + (Human a,Human b)
{
Human temp = new Human(a.s1 + b.s1, a.s2 + b.s2);
return temp;
}
public static Human operator - (Human a,Human b)
{
Human temp = new Human(a.s1 - b.s1, a.s2 - b.s2);
return temp;
}
public static bool operator == (Human a,Human b)
{
return a.s1 == b.s1 && a.s2 == b.s2;
}
public static bool operator !=(Human a,Human b)
{
return !(a == b);
}
}
public struct Coord
{
public int x;
public int y;
- / % & | ^ << >> == != > < >= <=
public Coord(int _x, int _y)
{
this.x = _x;
this.y = _y;
}
//operator:重置内置运算符,C#要求成对重载比较运算符
public static bool operator !=(Coord _c1,Coord _c2)
{
return !(_c1 == _c2);
}
public static bool operator ==(Coord _c1,Coord _c2)
{
return (_c1.x == _c2.x && _c1.y == _c2.y);
}
} -