Chomper Stomping jQuery/JavaScript/CSS 3/HTML 5, Java/PHP/Python/ActionScript, Git, Chrome/Firefox Extensions, Wordpress/Game/iPhone App Development and other random techie tidbits I've collected

28Aug/092

Finding the number of hex tiles inside of a hex shaped grid…

EDIT: There is a mathematical formula that is much better than the method I illustrate below. It is: 3n^2 - 3n + 1

A huge thanks to Sam Hughes for very patiently helping me out with this formula. He's the best mathematician I know...

Here's the JavaScript code to execute this formula (just change maxTiles to be however wide your hex grid is):

	var maxTiles = 7;	
	var n = Math.ceil((maxTiles - 2) / 2);
	var numberTiles = 3 * Math.pow(n, 2) - 3 * n + 1;

Below is the original post:


This is kind of like finding the area of a hex grid, except that for some reason none of the formulas I found for doing that would work. Also, finding the area of a triangle made of hex grids won't work with the normal triangle area formula either.

What I am illustrating here is how to find out how many hex tiles are inside of a hex shaped grid of hex tiles.

Here is a picture of the grid:

What you have to do is:

1. Take the half the width of the hex grid rounded down. So, if the hex grid is 7 wide, you take half of seven, 3.5, and round it down to 3. This can also be called "flooring" the number.
2. Take that number and use it to seed a floor loop, which counts down from that number, adding the new number to a grand total each time.
3. Multiply that grand total by 7 and add one for the middle tile (which never got counted).

Here is the code:

	var triangleTotal = 0;
	for(var spaces = Math.ceil((maxTiles-1)/2); spaces > 0; spaces--){
		triangleTotal += spaces;
	}
	var triangles = triangleTotal * 6;
	var numberTiles = triangles + 1;
	return numberTiles;

You'll notice that I took the total minus 1 divided by 2 and "ceil"ed it, instead of taking the total divided by two and "floor"ing it. It doesn't matter which you do...

Here's a visualization proving this out:


I only took one math class in college, otherwise this would have probably been very obvious to me as it may seem to you. There is probably even a really fancy easy little formula for this, but I don't know it and couldn't find it...

Here's a page where you can test this formula out in action. Note that a hex is always going to be an odd number of hexes wide, so if you enter an even number and get a funny shaped hex, this formula isn't going to work...

Comments (2) Trackbacks (0)
  1. What if the hexagonal is not a regular hexagon?

  2. Uh… I have no idea. I’m not even sure what that means, sorry :(


Leave a comment

No trackbacks yet.