Hexagon coloring

 from Red Blob Games
09 Jan 2019, updated 29 Oct 2023

This stackoverflow question asks about coloring a hex grid[1]. You can define a function color(hex) = (hex.q - hex.r) mod 3 to get three colors: 0, 1, and 2. Hover or tap on a hex to see the calculation:

Note that % is not the mod operator in some languages. You'll need ((q-r) % 3 + 3) % 3 to calculate mod 3. Further reading: mod and remainder are not the same[2].

One thing we can do with a three-color assignment is assign a rock-scissors-paper style winner/loser to each hexagon edge. In this diagram, redblue, bluegreen, and greenred:

Hexagon H beats neighbor N when color(H) = (color(N) + 1) mod 3. Thanks to Sagie Levy[3] for pointing out this use of hexagon coloring.

Source code for the diagrams on this page

Email me , or tweet @redblobgames, or comment: