How do I color a hexagonal grid such that it doesn’t have neighbors of the same color?

In a hex grid you’ll need three colors to color each hex so that it doesn’t have the same color as a neighbor:

You were on the right track with your solution. Instead of adding x+y you’ll want to subtract x-y. The other change is that &3 is for bit manipulation; you’ll want %3 instead. However, in some languages, including Javascript, %3 can return a negative number, so you’ll need to use ((___%3)+3)%3 to make it positive.

The color/sprite id you want is ((x-y)%3 + 3) % 3. I made an interactive demo to test this.

Leave a Comment