xxxxxxxxxx
95
const GRID_WIDTH = 10;
const GRID_HEIGHT = 6;
const TILE_RADIUS = 30;
// r**2 = h**2 + (r/2)**2
// h**2 = r**2 - (r/2)**2
// h**2 = r**2 - r**2/4
// h**2 = 3*r**2/4
const TILE_HEIGHT = Math.sqrt(3 * TILE_RADIUS**2 / 4);
function setup() {
createCanvas(TILE_RADIUS*1.5 * GRID_WIDTH + TILE_RADIUS, TILE_HEIGHT * 2 * GRID_HEIGHT + TILE_HEIGHT);
}
let playerX = GRID_WIDTH / 2;
let playerY = GRID_HEIGHT / 2;
function draw() {
background(0x18);
for (let y = 0; y < GRID_HEIGHT; y++) {
let trueY = y * TILE_HEIGHT * 2 + TILE_HEIGHT;
let nextDiff = TILE_HEIGHT;
for (let x = 0; x < GRID_WIDTH; x++) {
let trueX = x * TILE_RADIUS*1.5 + TILE_RADIUS;
fill(50);
if (x === playerX && y === playerY) fill("magenta");
stroke(255);
strokeWeight(1);
hexagon(trueX, trueY, TILE_RADIUS);
for (const kee in dirsMap()) {
const [mx, my] = movePlayer(kee);
if (mx === x && my === y) {
stroke(255);
fill(255);
textAlign(CENTER, CENTER);
textSize(TILE_RADIUS / 2);
text(kee, trueX, trueY);
break;
}
}
trueY += nextDiff;
nextDiff *= -1;
}
}
}
const EVEN_DIRS = {
"Q": [-1, -1],
"W": [0, -1],
"E": [1, -1],
"A": [-1, 0],
"S": [0, 1],
"D": [1, 0]
};
const ODD_DIRS = {
"Q": [-1, 0],
"W": [0, -1],
"E": [1, 0],
"A": [-1, 1],
"S": [0, 1],
"D": [1, 1]
};
function dirsMap() {
return playerX % 2 === 0 ? EVEN_DIRS : ODD_DIRS;
}
function movePlayer(kee) {
let dir = dirsMap()[kee];
return [playerX + dir[0], playerY + dir[1]];
}
function keyPressed() {
const dirs = dirsMap();
if (key.toUpperCase() in dirs) {
let dir = dirs[key.toUpperCase()];
playerX += dir[0];
playerY += dir[1];
}
}
function hexagon(cx, cy, radius) {
beginShape();
for (let angle = 0; angle < TAU; angle += TAU/6) {
const vx = cx + cos(angle)*radius;
const vy = cy + sin(angle)*radius;
vertex(vx, vy);
}
endShape(CLOSE);
}