- Completely agree with Jesse concerning mutable structs - it's hard to always remember to mutate proper variable.
- If you're very concerned about memory consumption (if that's the main reason for using mutable structs) I would rather use a bitmap for storing hasSides.
- I'll also use simplification of
CheckBounds
proposed by Jesse (and ReSharper :)).
Dictionary
(that MattDavey suggested to improve) is not needed at all... I don't see the reason for creating collection of hexagons just to iterate on it later, it's better to do the "EvaluateNeighbor" inline.
- And the last simplification that will reduce most of the code: all your
CheckBounds
can be combined in a simple loop if you extract the definition of "neighbors" in a separate array.
As a result I've got the following code:
static readonly Tuple<int, int>[][] _neighbors = new[] //TODO: rename to whatever you find appropriate
{
new[]
{
Tuple.Create(0,1),
Tuple.Create(1,0),
Tuple.Create(0,-1),
Tuple.Create(-1,-1),
Tuple.Create(-1,0),
Tuple.Create(-1,+1)
},
new[]
{
Tuple.Create(1,1),
Tuple.Create(1,0),
Tuple.Create(1,-1),
Tuple.Create(0,-1),
Tuple.Create(-1,0),
Tuple.Create(0,+1)
}
};
private static bool HasSide(Hexagon neighbor, Hexagon currentHexagon)
{
return currentHexagon.Height >= neighbor.Height &&
!MathExtensions.NearlyEqual(currentHexagon.Height, neighbor.Height);
}
private static bool CheckBounds(int x, int y)
{
return (x >= 0) && (x < regionDimensions) &&
(y >= 0) && (y < regionDimensions);
}
And the main iterator:
// Evaluate heights of hexagons and cull sides
for (var x = 0; x < regionDimensions; x++)
for (var y = 0; y < regionDimensions; y++)
{
var activeMapping = _neighbors[y % 2]; //TODO: rename to whatever you find more appropriate
for (int i = 0; i < activeMapping.Length; i++)
{
var shiftToCurrentCell = activeMapping[i];
var neighborX = x + shiftToCurrentCell.Item1;
var neighborY = y + shiftToCurrentCell.Item2;
hexagonArray[x, y].HasSides[i] = CheckBounds(neighborX, neighborY) &&
HasSide(hexagonArray[neighborX, neighborY], hexagonArray[x, y]);
}
}