Displaying a Hex Grid

Learn to display a hex grid on the console in Ruby.

Displaying a hexagon grid using corner coordinates

To display a hex grid, we need to be able to compute the coordinates of each of its corners or vertices. We’ll see how to compute those coordinates relative to the center of each hexagon, as well as how to compute the overall dimensions of a hex grid, and then we’ll plug that all into a new to_png implementation.

We’re going to assume that our grid is composed of regular hexagons (hexagons whose sides are all the same length). With that assumption, there is a small derivation involving equilateral triangles (triangles whose sides are all equal) that lets us get the measurements we need. In the context of this course, we’ll skip the derivation itself, but you are encouraged to try it yourself.

Essentially, what we want are lengths of a1a_1,a2a_2, and bb in the following diagram:

Get hands-on with 1200+ tech skills courses.