我正在使用C#,并使用2d结构数组构成一个瓦片网格。这与如何从网格中的瓦片中查找8个相邻瓦片无关。我知道在C#中,您可以让一系列的收益率产生可数的。喜欢:
public IEnumerable<int> fakeList()
{
yield return 1;
yield return 2;
}
并使用foreach循环调用它。现在,在我的网格类中,希望有一种简单的方法来访问并修改grid.array [x,y]中的邻居。但是由于它是一个结构体,所以我不能编写类似以下的迭代器:
public IEnumerable<int> neighbours(int x, int y)
{
if((x+1) >=0 && y >=0 && .....)//check if node above is inside grid
yield return grid.array[x+1,y];
//rinse and repeat 7 more times for each direction
}
相反,每次我需要邻居时,我都需要复制粘贴8if条件,并检查我是否使用正确的x + direction,y + direction来找到有效的索引。基本上,这是一个巨大的痛苦。
我可以通过以下方法解决:
第二种方法有效吗?还是会产生垃圾?我不知道收益率的详细运作方式。
public struct GridTile
{
public int x;
public int z;
public GridTile(int x, int z)
{
this.x = x;
this.z = z;
}
}
public IEnumerable<int> neighbours(int x, int y)
{
if ((x + 1) >= 0 && y >= 0 && .....)//check if right node is inside
yield return new Gridtile(x + 1, y);
//rinse and repeat 7 more times for each direction
}
如果您知道2D数组条目的坐标,则可以使用循环来检索邻居:
var twoD = new int[10,10];
var someX = 5;
var someY = 5;
List<int> neighbors = new List<int>();
for(int nx = -1; nx <= 1; nx++){
for(int ny = -1; ny <= 1; ny++){
int iX = someX + nX;
int iY = someY + nY;
if(iX > 0 && iX < twoD.GetLength(0) && iY > 0 && iY < twoD.GetLength(1))
neighbors.Add(twoD[iX,iY]);
}
}