<h1>Hex Grid Path Drawer</h1>
<p>Unhighlighted edges are thin. Hover or click to make them thick and bright.</p>
<div id="grid-container">
<svg id="hex-grid-svg"></svg>
</div>
<script>
// The JavaScript is identical to the previous version.
// All changes were made in the CSS.
document.addEventListener('DOMContentLoaded', function() {
const GRID_COLS = 12;
const GRID_ROWS = 8;
const HEX_RADIUS = 40;
const EDGE_INSET = 2;
const TAPER_AMOUNT = 6;
const svg = document.getElementById('hex-grid-svg');
const svgEdgesGroup = document.createElementNS('http://www.w3.org/2000/svg', 'g');
const svgHitboxGroup = document.createElementNS('http://www.w3.org/2000/svg', 'g');
svg.appendChild(svgEdgesGroup);
svg.appendChild(svgHitboxGroup);
const HEX_WIDTH = Math.sqrt(3) * HEX_RADIUS;
const HEX_HEIGHT = 2 * HEX_RADIUS;
function getHexVertices(centerX, centerY, radius) {
const vertices = [];
for (let i = 0; i < 6; i++) {
const angle = (Math.PI / 180) * (60 * i + 30);
const x = centerX + radius * Math.cos(angle);
const y = centerY + radius * Math.sin(angle);
vertices.push({ x, y });
}
return vertices;
}
function handlePolygonClick(event) {
const edgeId = event.currentTarget.dataset.edgeId;
document.getElementById(edgeId)?.classList.toggle('active');
}
function handlePolygonMouseOver(event) {
const edgeId = event.currentTarget.dataset.edgeId;
document.getElementById(edgeId)?.classList.add('hover-preview');
}
function handlePolygonMouseOut(event) {
const edgeId = event.currentTarget.dataset.edgeId;
document.getElementById(edgeId)?.classList.remove('hover-preview');
}
for (let row = 0; row < GRID_ROWS; row++) {
for (let col = 0; col < GRID_COLS; col++) {
const xOffset = (row % 2 === 1) ? HEX_WIDTH / 2 : 0;
const centerX = (col * HEX_WIDTH) + xOffset;
const centerY = row * HEX_HEIGHT * 0.75;
const outerRadius = HEX_RADIUS - EDGE_INSET;
const innerRadius = HEX_RADIUS - EDGE_INSET - TAPER_AMOUNT;
const outerVertices = getHexVertices(centerX, centerY, outerRadius);
const innerVertices = getHexVertices(centerX, centerY, innerRadius);
const hitboxVertices = getHexVertices(centerX, centerY, HEX_RADIUS);
for (let i = 0; i < 6; i++) {
const edgeId = `edge-${row}-${col}-${i}`;
const op1 = outerVertices[i];
const op2 = outerVertices[(i + 1) % 6];
const ip1 = innerVertices[i];
const ip2 = innerVertices[(i + 1) % 6];
const edge = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
edge.setAttribute('points', `${op1.x},${op1.y} ${op2.x},${op2.y} ${ip2.x},${ip2.y} ${ip1.x},${ip1.y}`);
edge.setAttribute('id', edgeId);
edge.setAttribute('class', 'hex-edge');
svgEdgesGroup.appendChild(edge);
const hp1 = hitboxVertices[i];
const hp2 = hitboxVertices[(i + 1) % 6];
const hitbox = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
hitbox.setAttribute('points', `${centerX},${centerY} ${hp1.x},${hp1.y} ${hp2.x},${hp2.y}`);
hitbox.dataset.edgeId = edgeId;
hitbox.setAttribute('class', 'hitbox-polygon');
hitbox.addEventListener('click', handlePolygonClick);
hitbox.addEventListener('mouseover', handlePolygonMouseOver);
hitbox.addEventListener('mouseout', handlePolygonMouseOut);
svgHitboxGroup.appendChild(hitbox);
}
}
}
const svgWidth = (GRID_COLS * HEX_WIDTH) + (HEX_WIDTH / 2);
const svgHeight = ((GRID_ROWS - 1) * HEX_HEIGHT * 0.75) + HEX_HEIGHT;
const padding = HEX_RADIUS;
svg.setAttribute('viewBox', `${-padding} ${-padding} ${svgWidth + padding * 2} ${svgHeight + padding * 2}`);
});
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Hex Sokoban</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
margin: 0;
background-color: #f0f2f5;
user-select: none;
}
h1 {
color: #333;
margin: 10px 0 0 0;
}
#grid-container {
width: 90vw;
max-width: 900px;
height: 80vh;
max-height: 700px;
border: 1px solid #ccc;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
background-color: #fff;
position: relative;
}
svg {
width: 100%;
height: 100%;
}
.hex-edge {
fill: transparent;
stroke: #bbb;
stroke-width: 1px;
transition: all 0.15s ease-in-out;
pointer-events: none;
}
.hex-edge.active {
fill: #e74c3c;
stroke: #c0392b;
}
.hex-edge.hover-preview {
fill: #3498db;
stroke: #2980b9;
}
.hitbox-polygon {
fill: transparent;
stroke: none;
cursor: pointer;
}
.crate-piece {
pointer-events: none;
}
.player-circle {
fill: #2ecc71;
stroke: #27ae60;
stroke-width: 3px;
pointer-events: none;
}
#instructions {
max-width: 900px;
margin: 10px 20px 20px 20px;
color: #555;
font-size: 14px;
line-height: 1.4;
}
</style>
</head>
<body>
<h1>Hex Sokoban</h1>
<div id="instructions">
Use keys <b>D E W A S Z</b> to move the player in the six hex directions:<br/>
D=East(0), E=NE(1), W=NW(2), A=West(3), S=SW(4), Z=SE(5).<br/>
Push and merge crate pieces until one crate has all 6 edges.<br/>
Player can stand on crates.<br/>
Enjoy!
</div>
<div id="grid-container">
<svg id="hex-grid-svg"></svg>
</div>
<script>
(() => {
// Constants
const GRID_COLS = 9;
const GRID_ROWS = 7;
const HEX_RADIUS = 40;
const EDGE_INSET = 2;
const TAPER_AMOUNT = 6;
// Directions: q,r offsets for axial coords
const DIRECTIONS = [
{q: +1, r: 0}, // 0 E
{q: +1, r: -1}, // 1 NE
{q: 0, r: -1}, // 2 NW
{q: -1, r: 0}, // 3 W
{q: -1, r: +1}, // 4 SW
{q: 0, r: +1} // 5 SE
];
// Opposite direction helper
function oppositeDir(d) {
return (d + 3) % 6;
}
// Axial to pixel conversion
const HEX_WIDTH = Math.sqrt(3) * HEX_RADIUS;
const HEX_HEIGHT = 2 * HEX_RADIUS;
function axialToPixel(q, r) {
// Offset for odd-r layout
const x = HEX_WIDTH * (q + (r % 2) / 2);
const y = HEX_HEIGHT * (r * 0.75);
return {x, y};
}
// Get hex vertices for drawing edges
function getHexVertices(centerX, centerY, radius) {
const vertices = [];
for (let i = 0; i < 6; i++) {
const angle = (Math.PI / 180) * (60 * i + 30);
const x = centerX + radius * Math.cos(angle);
const y = centerY + radius * Math.sin(angle);
vertices.push({ x, y });
}
return vertices;
}
// Data structures
// Map from "q,r" string to crate piece or null
// Crate piece: { edges: Set of edges (0-5) }
// Player: {q, r}
// Helper to stringify coords
function coordKey(q, r) {
return `${q},${r}`;
}
// Parse key back to coords
function parseKey(key) {
const [q, r] = key.split(',').map(Number);
return {q, r};
}
// Check if coords are inside grid
function inGrid(q, r) {
// Simple rectangular bounds for axial coords
// We'll allow q in [0, GRID_COLS-1], r in [0, GRID_ROWS-1]
// but since odd-r offset, q can be fractional in pixel space
return q >= 0 && q < GRID_COLS && r >= 0 && r < GRID_ROWS;
}
// Game state
const crates = new Map(); // key: "q,r" -> {edges: Set}
let player = {q: 1, r: 3};
// Initialize some crates for demo
// We'll place 4 crate pieces scattered with some edges
// Each crate piece starts with a single edge for simplicity
// Player starts on empty tile
function addCrate(q, r, edges) {
crates.set(coordKey(q, r), {edges: new Set(edges)});
}
// Example initial crates (can be changed)
addCrate(3, 3, [0]);
addCrate(4, 3, [3]);
addCrate(3, 4, [5]);
addCrate(2, 4, [2]);
// SVG setup
const svg = document.getElementById('hex-grid-svg');
svg.innerHTML = ''; // clear
// Groups for layers
const edgesGroup = document.createElementNS('http://www.w3.org/2000/svg', 'g');
const cratesGroup = document.createElementNS('http://www.w3.org/2000/svg', 'g');
const playerGroup = document.createElementNS('http://www.w3.org/2000/svg', 'g');
svg.appendChild(edgesGroup);
svg.appendChild(cratesGroup);
svg.appendChild(playerGroup);
// Precompute hex grid positions for all tiles
const hexCenters = new Map(); // key -> {x,y}
for(let r=0; r<GRID_ROWS; r++) {
for(let q=0; q<GRID_COLS; q++) {
const {x, y} = axialToPixel(q, r);
hexCenters.set(coordKey(q,r), {x, y});
}
}
// Draw hex grid edges (background)
function drawGridEdges() {
edgesGroup.innerHTML = '';
for(let r=0; r<GRID_ROWS; r++) {
for(let q=0; q<GRID_COLS; q++) {
const center = hexCenters.get(coordKey(q,r));
if(!center) continue;
const outerRadius = HEX_RADIUS - EDGE_INSET;
const innerRadius = HEX_RADIUS - EDGE_INSET - TAPER_AMOUNT;
const outerVertices = getHexVertices(center.x, center.y, outerRadius);
const innerVertices = getHexVertices(center.x, center.y, innerRadius);
for(let i=0; i<6; i++) {
const op1 = outerVertices[i];
const op2 = outerVertices[(i+1)%6];
const ip1 = innerVertices[i];
const ip2 = innerVertices[(i+1)%6];
const poly = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
poly.setAttribute('points', `${op1.x},${op1.y} ${op2.x},${op2.y} ${ip2.x},${ip2.y} ${ip1.x},${ip1.y}`);
poly.setAttribute('class', 'hex-edge');
edgesGroup.appendChild(poly);
}
}
}
}
// Draw crates
// Each crate piece draws its edges as active hex-edge polygons on top of the grid
// We'll create one group per crate piece for easy update
function drawCrates() {
cratesGroup.innerHTML = '';
for(const [key, crate] of crates.entries()) {
const center = hexCenters.get(key);
if(!center) continue;
const outerRadius = HEX_RADIUS - EDGE_INSET;
const innerRadius = HEX_RADIUS - EDGE_INSET - TAPER_AMOUNT;
const outerVertices = getHexVertices(center.x, center.y, outerRadius);
const innerVertices = getHexVertices(center.x, center.y, innerRadius);
const crateGroup = document.createElementNS('http://www.w3.org/2000/svg', 'g');
crateGroup.setAttribute('class', 'crate-piece');
crateGroup.setAttribute('data-coord', key);
for(let i=0; i<6; i++) {
if(crate.edges.has(i)) {
const op1 = outerVertices[i];
const op2 = outerVertices[(i+1)%6];
const ip1 = innerVertices[i];
const ip2 = innerVertices[(i+1)%6];
const poly = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
poly.setAttribute('points', `${op1.x},${op1.y} ${op2.x},${op2.y} ${ip2.x},${ip2.y} ${ip1.x},${ip1.y}`);
poly.setAttribute('class', 'hex-edge active');
crateGroup.appendChild(poly);
}
}
cratesGroup.appendChild(crateGroup);
}
}
// Draw player as a circle on top of crates
function drawPlayer() {
playerGroup.innerHTML = '';
const center = hexCenters.get(coordKey(player.q, player.r));
if(!center) return;
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
circle.setAttribute('cx', center.x);
circle.setAttribute('cy', center.y);
circle.setAttribute('r', HEX_RADIUS * 0.4);
circle.setAttribute('class', 'player-circle');
playerGroup.appendChild(circle);
}
// Render all
function render() {
drawGridEdges();
drawCrates();
drawPlayer();
}
// Game logic helpers
// Get crate piece at q,r or null
function getCrate(q, r) {
return crates.get(coordKey(q, r)) || null;
}
// Set crate piece at q,r (or remove if null)
function setCrate(q, r, crate) {
const key = coordKey(q, r);
if(crate === null) {
crates.delete(key);
} else {
crates.set(key, crate);
}
}
// Check if two crates can merge (no conflicting edges)
// Conflicting edges = edges that overlap but differ?
// Actually, edges are sets of directions. Merging means union.
// Conflict if they share an edge that is missing in one? No conflict.
// Conflict if they have edges that are opposite? No.
// The spec says "attempting to merge two pieces that have conflicting Edges" is invalid.
// Let's interpret conflict as: if the two crates have edges that overlap but are not the same?
// Since edges are sets, conflict means if they have edges that overlap but one crate is missing an edge that the other has on the contacting side?
// Actually, the spec says "A Crate can push the next one in the chain only if their contacting Edges both exist."
// So conflict means if the union of edges has duplicates? No, sets handle that.
// So conflict means if the crates have edges that contradict? The spec is ambiguous.
// We'll interpret conflict as: no conflict if edges sets can be unioned without contradiction.
// So no conflict if union is possible.
// So conflict means: if the crates have edges that overlap but are different? Impossible for sets.
// So no conflict in merging edges.
// We'll just allow merging if union of edges is valid (always true).
// But the spec says "A push is blocked if any merge in the chain is invalid (i.e., attempting to merge two pieces that have conflicting Edges)."
// So maybe conflict means if the crates have edges that overlap but are not the same? They are sets, so no conflict.
// We'll assume no conflict in merging edges.
// So no conflict check needed for edges.
// Check if two crates can push each other in direction d:
// Both must have the contacting edges:
// Crate1 must have edge d
// Crate2 must have edge oppositeDir(d)
function canPushPair(crate1, crate2, d) {
return crate1.edges.has(d) && crate2.edges.has(oppositeDir(d));
}
// Build push chain starting from playerTile or destTile depending on inside/outside push
// Returns array of {q,r,crate} in push order (front is furthest crate)
// Also returns if push is valid
function buildPushChain(startQ, startR, d) {
const chain = [];
let currentQ = startQ;
let currentR = startR;
let prevCrate = null;
while(true) {
const crate = getCrate(currentQ, currentR);
if(!crate) break;
if(prevCrate) {
// Check contacting edges between prevCrate and crate
if(!canPushPair(prevCrate, crate, d)) {
return {valid: false, chain: []};
}
}
chain.push({q: currentQ, r: currentR, crate});
prevCrate = crate;
currentQ += DIRECTIONS[d].q;
currentR += DIRECTIONS[d].r;
if(!inGrid(currentQ, currentR)) {
// Can't push off grid
return {valid: false, chain: []};
}
// Check next tile for crate
if(!getCrate(currentQ, currentR)) {
// Empty tile found, chain ends here
break;
}
}
return {valid: true, chain};
}
// Merge two crates: union edges
function mergeCrates(crateA, crateB) {
const newEdges = new Set([...crateA.edges, ...crateB.edges]);
return {edges: newEdges};
}
// Check if crate has all edges (win condition)
function isCompleteCrate(crate) {
for(let i=0; i<6; i++) {
if(!crate.edges.has(i)) return false;
}
return true;
}
// Player move attempt in direction d
function attemptMove(d) {
const playerKey = coordKey(player.q, player.r);
const destQ = player.q + DIRECTIONS[d].q;
const destR = player.r + DIRECTIONS[d].r;
const destKey = coordKey(destQ, destR);
if(!inGrid(destQ, destR)) {
// Outside grid, blocked
return;
}
const playerCrate = getCrate(player.q, player.r);
const destCrate = getCrate(destQ, destR);
// Step 1: Determine if Push Attempt
// Inside Push: playerTile has crate with edge d
// Outside Push: destTile has crate with edge oppositeDir(d)
const insidePush = playerCrate && playerCrate.edges.has(d);
const outsidePush = destCrate && destCrate.edges.has(oppositeDir(d));
if(insidePush || outsidePush) {
// Push attempt
// Determine push chain start tile
let pushStartQ, pushStartR;
if(insidePush) {
pushStartQ = player.q;
pushStartR = player.r;
} else {
pushStartQ = destQ;
pushStartR = destR;
}
const {valid, chain} = buildPushChain(pushStartQ, pushStartR, d);
if(!valid) {
// Push blocked
return;
}
// Execute push: move chain one tile forward, merging crates if needed
// Move from furthest crate to closest
// For each crate in chain:
// - Check if next tile has crate: if yes, merge
// - Else move crate to next tile
// We'll do merges from front to back
for(let i = chain.length - 1; i >= 0; i--) {
const {q, r, crate} = chain[i];
const nextQ = q + DIRECTIONS[d].q;
const nextR = r + DIRECTIONS[d].r;
const nextCrate = getCrate(nextQ, nextR);
if(nextCrate) {
// Merge crates
const merged = mergeCrates(crate, nextCrate);
setCrate(nextQ, nextR, merged);
setCrate(q, r, null);
} else {
// Move crate forward
setCrate(nextQ, nextR, crate);
setCrate(q, r, null);
}
}
// Move player to destTile
player.q = destQ;
player.r = destR;
// Check win condition
for(const crate of crates.values()) {
if(isCompleteCrate(crate)) {
setTimeout(() => alert("You Win! The crate is complete."), 10);
break;
}
}
} else {
// Simple move
// Allowed if destTile empty or contains crate but not outside push
// So player can move onto empty or onto crate tile (player can co-exist)
player.q = destQ;
player.r = destR;
}
render();
}
// Keyboard controls
// Map keys to directions
const keyToDir = {
'd': 0, // E
'e': 1, // NE
'w': 2, // NW
'a': 3, // W
's': 4, // SW
'z': 5 // SE
};
window.addEventListener('keydown', e => {
const key = e.key.toLowerCase();
if(key in keyToDir) {
e.preventDefault();
attemptMove(keyToDir[key]);
}
});
// Initial render
render();
// Expose for debugging (optional)
window.hexSokoban = {
crates,
player,
attemptMove,
render,
};
})();
</script>
</body>
</html>