How do I represent a hextile/hex grid in memory?

Amit Patel has posted an amazing page on this topic. It's so comprehensive and wonderful that it needs to be the definitive answer to this question: Hexagonal Grids

cubez


Such a grid can be represented in a two-dimensional array:

If

   2
7     3
   1   
6     4
   5

is the number one with its neighbors in the hex grid, then you can put this into a 2D array like so:

2 3
7 1 4
  6 5

Obviously neighbor-ness is determined in this grid not only by being horizontally or vertically adjacent but also using one diagonal.

You can use a graph too, if you like to, though.


This article goes through how to set up a Isomeric/Hexagonal grid game. I recommend you have a look at the Forcing Isometric and Hexagonal Maps onto a Rectangular Grid section and the the movement section. Although it is different from what you are looking for it may help you formulate how to do what you want.


I've dealt a lot with hexes. In cases like this, you track each of the 6 points for the borders of the hex. This lets you draw it quite easily.

You would have a single array of objects that represent hexes. Each of these hex objects also has 6 "pointers" (or an index to another array) pointing to another array of "sides". Same thing for "vertices". Of course the vertices would have 3 pointers to the adjoining hexes, and the sides would have 2.

So, a hex may be something like: X, Y, Point(6), Vertices(6), Sides(6)

Then you have a Hex array, vertice array, and side array.

Then it is pretty simple to find the vertices/sides for a hex, or whatever.

When I say pointer it could just as easily be an integer pointing to the element in the vertice or side array or whatever. And of course arrays could be lists or whatever.


You could create a 2D array and then consider the valid positions as:

  • On even-numbered rows (0,2,4,...): the odd numbered cells.
  • On odd-numbered rows (1,3,5,...): the even numbered cells.

For each cell, its neighbors would be:

  • Same column, 2 rows up
  • Same column, 2 rows down
  • 1 left + 1 up
  • 1 left + 1 down
  • 1 right + 1 up
  • 1 right + 1 down

Illustration:

Hex Grid

The x marks are hexes. x that are diagonal to each other are neighbors. | connects vertical neighbors.