..O Deniz's personal pages
/home /about

Hex grid backing arrays

May 9, 2018

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


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:

createMatrix: (radius) ->
        mid = Math.floor(radius/2)
        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

Tags: #programming