Hex Grid representation
Trying this: http://gamedev.stackexchange.com/a/44814/944
(also check: http://playtechs.blogspot.ca/2007/04/hex-grids.html)
HTML
<div id="hex-grid">
</div>
CSS
#hex-grid {
width: 700px;
height: 480px;
background-color: #333;
}
.hex {
stroke-width: 1px;
cursor: pointer;
stroke: #222;
fill: #555;
}
.hex-grass {
fill: #01A611;
}
.hex-water {
fill: #0375B4;
}
.hex-water.hex-elevation-minus-2 {
fill: #004070;
}
.hex-mountain {
fill: #777;
}
.hex-mountain.hex-elevation-5 {
fill: #f0f0f0;
}
JavaScript
var gridElem = $('#hex-grid'),
sqrGrid = [],
hexR = 26,
hexH = 2 * hexR,
margin = 20,
hexW = hexH * Math.cos(Math.PI / 6),
gridW = gridElem.width(),
gridH = gridElem.height(),
maxCol = Math.floor((gridW - 2 * margin) / hexW),
maxRow = Math.floor((gridH - 2 * margin) / (3 * hexR / 2)),
maxElevation = 5,
minElevation = -2;
var HexTypes = {
water: 'water',
grass: 'grass',
mountain: 'mountain'
};
var Directions = {
ne: 'ne',
e: 'e',
se: 'se',
sw: 'sw',
w: 'w',
nw: 'nw'
};
generateGrid();
renderGrid(hexGrid);
// -------------------------------------------------------------------------------------------
function generateGrid() {
for(var i = 0; i < maxCol; i++) {
hexGrid[i] = [];
for(var j = 0; j < maxRow; j++) {
hexGrid[i][j] = {
col: i,
row: j,
type: HexTypes.grass
};
}
}
populateWorld();
}
function populateWorld() {
var hex,
i, j;
setElevations();
// Water
for(i = 0; i < maxCol; i++)
for(j = 0; j < maxRow; j++) {
hex = hexGrid[i][j];
if(hex.elevation < 0) {
hex.type = HexTypes.water;
} else if(hex.elevation > 2) {
hex.type = HexTypes.mountain;
}
}
}
function setElevations() {
for(i = 0; i < maxCol; i++)
for(j = 0; j < maxRow; j++) {
hexGrid[i][j].elevation =
Math.round(Math.random() * (maxElevation + Math.abs(minElevation)) - Math.abs(minElevation));
}
}
function renderGrid(hexGrid) {
var hex,
html = '<svg width="' + gridW + '" height="' + gridH + '" xmlns="http://www.w3.org/2000/svg">';
for(var i = 0; i < maxCol; i++)
for(var j = 0; j < maxRow; j++)
html += getHexHtml(i, j);
html += '</svg>';
gridElem.html(html);
}
function getHexX(col, row) {
return margin
...