Hex grid backing arrays

stuff about computer science and programming
dendiz
Posts: 234
Joined: Wed Oct 10, 2018 3:48 am

Hex grid backing arrays

Programming game worlds with square grids is pretty straight forward. You just use a 2D array, and calculations are quite easy. To go up you subtract from the Y coordinate, to go left you add 1 to the X coordinate. But when you are dealing with hex grids life gets a bit more complicated. Representing a backing array for a hex grid can be done in the following way

Code: Select all

``````[
[null,null,null,{},{},{},{}],
[null,null,{},{},{},{},{}],
[null,{},{},{},{},{},{}],
[{},{},{},{},{},{},{}],
[{},{},{},{},{},{},null],
[{},{},{},{},{},null,null],
[{},{},{},{},null,null,null]
]
``````
this would be the representation array for the following grid

the row 3 in the array is the row in the center of the grid. If you go up one row the row becomes an element shorter (represented by a null element). You could also skip adding the null element and use different length elements for each row, but that brings it own advantages and disadvantages. The radius of the grid is defined as the length on the longest row for the hex shaped grid. Now for a given radius of N how could we generate the backing array for that grid?

The property to notice here is that the number of nulls increases from the middle out by one. So you would have abs(i - mid) number of null elements for a given row i where mid is floor(radius) /2. You would place these null elements in the beginning of the array if i < mid and at the end of the array if i > mid. Here is some coffeescript code that does this:

Code: Select all

``````createMatrix: (radius) ->
matrix = [1..radius].map (it, i) ->;
count = Math.abs(i - mid)
head = [0 ... count].map -> null
tail = [count + 1 .. radius].map (it) -> {}
if  i > 3 then head.concat tail else tail.concat head
matrix
``````