[英]Index is not in array issues - C#
I'm currently in the process of making mine sweeper for a class project.我目前正在为 class 项目制作扫雷机。 I have got most of the fundamentals but when I click on an edge button, because it checks all buttons around it, the code crashes when there is no index value.
我已经掌握了大部分基础知识,但是当我单击一个边缘按钮时,因为它会检查它周围的所有按钮,所以当没有索引值时代码会崩溃。 Eg When x is equal to 10 but the code calls for
buttonArray[x + 1, y]
.例如,当 x 等于 10 但代码调用
buttonArray[x + 1, y]
。 Its a null value and just crashes.它的 null 值只是崩溃。 Any Ideas on how to fix this?
有想法该怎么解决这个吗? Code is included...
包含代码...
decimal MineCount = 0;
#region MineCount
if ((buttonArray[x + 1, y] != null) && (isMine[x + 1, y] == true))
{
isNeighbour[x, y] = true;
isBlank[x, y] = false;
MineCount += 1m;
}
if ((buttonArray[x + 1, y + 1] != null) && (isMine[x + 1, y + 1] == true))
{
isNeighbour[x, y] = true;
isBlank[x, y] = false;
MineCount += 1m;
}
if ((buttonArray[x + 1, y - 1] != null) && (isMine[x + 1, y - 1] == true))
{
isNeighbour[x, y] = true;
isBlank[x, y] = false;
MineCount += 1m;
}
if ((buttonArray[x, y + 1] != null) && (isMine[x, y + 1] == true))
{
isNeighbour[x, y] = true;
isBlank[x, y] = false;
MineCount += 1m;
}
if ((buttonArray[x, y - 1] != null) && (isMine[x, y - 1] == true))
{
isNeighbour[x, y] = true;
isBlank[x, y] = false;
MineCount += 1m;
}
if ((buttonArray[x - 1, y - 1] != null) && (isMine[x - 1, y - 1] == true))
{
isNeighbour[x, y] = true;
isBlank[x, y] = false;
MineCount += 1m;
}
if ((buttonArray[x - 1, y] != null) && (isMine[x - 1, y] == true))
{
isNeighbour[x, y] = true;
isBlank[x, y] = false;
MineCount += 1m;
}
if ((buttonArray[x - 1, y + 1] != null) && (isMine[x - 1, y + 1] == true))
{
isNeighbour[x, y] = true;
isBlank[x, y] = false;
MineCount += 1m;
}
You can use this function for this, instead of duplicate code.您可以为此使用此 function,而不是重复代码。 The point of the function is to use limited boundaries.
function 的要点是使用有限的边界。
void CountCells()
{
for(int ix = Math.Max(x - 1, 0); ix <= Math.Min(x + 1, isMine.GetLength(0)); ix++)
{
for(int iy = Math.Max(y - 1, 0); iy <= Math.Min(y + 1, isMine.GetLength(1)); iy++)
{
if ((buttonArray[ix,iy] != null) && isMine[ix,iy])
{
isNeighbour[ix, iy] = true;
isBlank[ix, iy] = false;
MineCount += 1m;
}
}
}
}
Hope it's can be helpfull!希望对您有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.