/* Returns true if coordinates C are invalid for grid size P */ public static bool OutOfBounds(this HexParameters P, HexCoordinates C) { int w = P.A; int h = P.Height(); if (C.Y < 0 || C.Y >= h) { return(true); } int offset = 0; int y = 0; while (y < C.Y) { y++; if (y >= P.B) { w--; offset++; } if (y < P.C) { w++; } } if (C.X < offset || C.X >= w + offset) { return(true); } return(false); }
/* Finds valid coordinate from input coordinate */ public static HexCoordinates FindInBounds(this HexParameters P, HexCoordinates C) { if (!ValidParameters(P)) { return(C); } HexCoordinates c = C; int h = P.Height(); while (P.OutOfBounds(c)) { if (c.Y < 0) { c = c.Shift(0, 1); } else if (c.Y >= h) { c = c.Shift(0, -1); } else if (c.X < 0 || c.X - c.Y + P.B <= 0) { c = c.Shift(1, 0); } else { c = c.Shift(-1, 0); } } return(c); }
/* Build array of HexCoordinates corresponding to a convex grid * First cell is (0,0); builds left-to-right, top-to-bottom */ public static HexCoordinates[] BuildHexGrid(HexParameters P) { int gridSize = P.GridSize(); HexCoordinates[] coordinates = new HexCoordinates[gridSize]; int i = 0; int w = P.A; int h = P.Height(); int offset = 0; int y = 0; while (y < h) { for (int x = 0; x < w; x++) { coordinates[i++] = new HexCoordinates(x + offset, y); } y++; if (y >= P.B) { w--; offset++; } if (y < P.C) { w++; } } return(coordinates); }