Reputation: 11
Iam trying to look at all neighbors of each entry in a two dimensional array using a foreach loop and two for loops. The problem iam running into is that I was getting an ArrayIndexOutOfBounds exception when looking through the edge cells. The only way I found to solve it was this really inefficient if else condition. I do not want to loop my array at the edges. Is there any more efficient way of getting around this issue?
foreach (Cell cell in playField._playField)
{
for (int dx = -1; dx <= 1; dx++)
{
for (int dy = -1; dy <= 1; dy++)
{
if (cell.PositionX + dx < 0 || cell.PositionX + dx >= XSize || cell.PositionY + dy < 0 || cell.PositionY + dy >= YSize)
break;
else
cell.Neighbors = _playField[cell.PositionX + dx, cell.PositionY + dy].IsMine ? cell.Neighbors + 1 : cell.Neighbors;
}
}
}
Upvotes: 1
Views: 80
Reputation: 9824
I call that the "Playing Field" problem of game design. I see two solutions:
a) Your "inefficient" construct of conditions. (my biggest worry about those is usually messing up. Those checks should have no relevant performance impact).
b) Add a "border" of cells around the Playing field. This border is not displayed. It exists purely so you can avoid that construct of conditions - you can stop all game-code if you hit a "border" cell during the neighbour check.
A Chess Board in memory would be 10x10 with this solution, with only the inner 8x8 making it onto the screen.
Upvotes: 1