xxxxxxxxxx
116
const BOARD_SIZE = 4;
const TILE_SIZE = 40;
let layout;
const hexes = [];
const homes = [
{owner: 0, hex: Hex(0, 3, -3)},
{owner: 0, hex: Hex(3, -3, 0)},
{owner: 0, hex: Hex(-3, 0, 3)},
{owner: 1, hex: Hex(3, 0, -3)},
{owner: 1, hex: Hex(-3, 3, 0)},
{owner: 1, hex: Hex(0, -3, 3)},
];
const grid = [];
function gridAt(grid, hex) {
for (const tile of grid) {
if (hexIsEquals(hex, tile.hex)) {
return tile;
}
}
throw new Error("gridAt() argument out of bounds");
}
function setup() {
createCanvas(windowWidth, windowHeight);
layout = hexLayout(pointyOrient, Point(TILE_SIZE, TILE_SIZE));
hexGenerateBoard(BOARD_SIZE - 1, hexes);
for (const hex of hexes) {
grid.push({hex, piece: -1});
}
for (const home of homes) {
gridAt(grid, home.hex).piece = home.owner;
}
}
function draw() {
background(0x18);
translate(width / 2, height / 2);
for (const hex of hexes) {
const loc = hex2Screen(layout, hex);
const coord = hexGetCoord(hex);
push();
fill("limegreen");
for (const home of homes) {
if (hexIsEquals(hex, home.hex)) {
fill(home.owner === 0 ? "white" : "black");
break;
}
}
if (currentHex !== null && hexIsEquals(hex, currentHex)) {
fill("red");
}
hexDraw(layout, hex);
pop();
push();
strokeWeight(4);
stroke("darkblue");
fill(gridAt(grid, hex).piece === 0 ? "white" : "black");
if (gridAt(grid, hex).piece !== -1) circle(loc.x, loc.y, TILE_SIZE);
if (currentHex !== null && hexInArray(hex, possibleMoves(grid, currentHex))) {
fill("lightgray");
noStroke();
circle(loc.x, loc.y, TILE_SIZE*0.8);
}
pop();
push();
fill("gray");
text(coord, loc.x, loc.y);
pop();
}
}
let currentHex = null;
function mousePressed() {
const mx = mouseX - width / 2;
const my = mouseY - height / 2;
const hex = screen2Hex(layout, Point(mx, my));
if (!inbounds(grid, hex)) return;
if (gridAt(grid, hex).piece !== -1) currentHex = hex;
if (currentHex !== null && hexInArray(hex, possibleMoves(grid, currentHex))) {
gridAt(grid, hex).piece = gridAt(grid, currentHex).piece;
currentHex = null;
}
}
function possibleMoves(grid, hex) {
const moves = [];
for (let i = 0; i < 6; i++) {
const neigh = hexGetNeighbor(hex, i);
if (inbounds(grid, hex)) {
moves.push(neigh);
}
}
return moves;
}
function inbounds(grid, hex) {
return grid.filter(tile => hexIsEquals(hex, tile.hex)).length > 0;
}
function hexInArray(hex, hexes) {
return hexes.filter(h => hexIsEquals(h, hex)).length > 0;
}