Skip to content

Instantly share code, notes, and snippets.

@pfgithub
Created August 8, 2020 07:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pfgithub/260f17c5e62095b99956ebfb66b42a0b to your computer and use it in GitHub Desktop.
Save pfgithub/260f17c5e62095b99956ebfb66b42a0b to your computer and use it in GitHub Desktop.
ywot
{
function makeBoard(fill) {
// it would be useful if board could center at 0,0 and expand infinitely
let board = [];
let limits;
let reso = {
clear: () => {
board = [];
},
get: (x, y) => {
if (!limits)
return fill;
if (x < limits.xmin ||
x > limits.xmax ||
y < limits.ymin ||
y > limits.ymax)
return fill;
if (!board[Number(y)])
return fill;
let bval = board[Number(y)][Number(x)];
return bval === undefined ? fill : bval;
},
set: (x, y, v) => {
if (!limits)
limits = {
xmin: Number(x),
ymin: Number(y),
xmax: Number(x),
ymax: Number(y),
};
if (x < limits.xmin)
limits.xmin = Number(x);
if (y < limits.ymin)
limits.ymin = Number(y);
if (x > limits.xmax)
limits.xmax = Number(x);
if (y > limits.ymax)
limits.ymax = Number(y);
if (!board[Number(y)])
board[Number(y)] = [];
board[Number(y)][Number(x)] = v;
},
forEach: visitor => {
if (!limits)
return;
let ym = limits.ymin;
let yma = limits.ymax;
let xm = limits.xmin;
let xma = limits.xmax;
for (let y = ym; y <= yma; y++) {
for (let x = xm; x <= xma; x++) {
visitor(reso.get(x, y), x, y);
}
}
},
copy: () => {
let nb = makeBoard(fill);
reso.forEach((v, x, y) => nb.set(x, y, v));
return nb;
},
print: (printer = v => v) => {
var res = "";
// ratelimit print
if (!limits)
return console.log("*no board to print*");
let ylength = 0;
for (let y = limits.ymin - 1; y <= limits.ymax + 1; y++) {
ylength = Math.max(y.toString().length, ylength);
}
res += (" ".repeat(ylength) +
" .-" +
"-".repeat(limits.xmax - limits.xmin + 3) +
"-.") + "\n";
for (let y = limits.ymin - 1; y <= limits.ymax + 1; y++) {
let line = "";
for (let x = limits.xmin - 1; x <= limits.xmax + 1; x++) {
line += printer(reso.get(x, y), x, y);
}
res += (y.toString().padStart(ylength, " ") + " | " + line + " |") + "\n";
}
res += (" ".repeat(ylength) +
" '-" +
"-".repeat(limits.xmax - limits.xmin + 3) +
"-'") + "\n";
return res;
},
};
return reso;
}
const board = makeBoard(" ");
const tileh = 8;
const tilew = 16;
for(let tc of [...document.querySelectorAll(".tilecont")]) {
let [y,x] = tc.getAttribute("data-tileyx").split(",").map(q => +q);
let [by, bx] = [y * tileh, x * tilew];
Array.from(tc.children[0].children[0].children).forEach((gridy, yp) => {
Array.from(gridy.children).forEach((gridtyl, xp) => {
board.set(bx + xp, by + yp, gridtyl.textContent);
});
});
}
copy(board.print());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment