Skip to content

Instantly share code, notes, and snippets.

@kaineer
Created May 6, 2026 05:46
Show Gist options
  • Select an option

  • Save kaineer/a391f531d24379fb2fc65ae8713eb2b9 to your computer and use it in GitHub Desktop.

Select an option

Save kaineer/a391f531d24379fb2fc65ae8713eb2b9 to your computer and use it in GitHub Desktop.
// util functions
const list = (arrLike) => Array.from(arrLike);
const first = (selector) => document.querySelector(selector);
const all = (selector) => list(document.querySelectorAll(selector));
const child = (el, index = 0) => list(el.children)[index];
const text = (el, value = null) => {
if (value === null) {
return el && el.textContent;
}
el.textContent = value;
};
const html = (el, value = null) => {
if (value === null) {
return el && el.innerHTML;
}
el.innerHTML = value;
};
const on = (el, eventType) => (fn) => el.addEventListener(eventType, fn);
const classes = (el, classObject = null) => {
const list = el.classList;
if (classObject === null) {
return {
has: (className) => list.contains(className),
add: (className) => list.add(className),
rm: (className) => list.remove(className),
toggle: (className, flag) => (list.toggle(className, flag), list),
};
}
Object.keys(classObject).forEach((key) => {
list.toggle(key, classObject[key]);
});
};
//
const interval = (size) => {
return Array(size)
.fill(0)
.map((_, i) => i);
};
// item
const createItem = (y) => (x) => {
return "<div class='item' data-pos='" + x + ":" + y + "'></div>";
};
const joinMap = (items, fn) => {
return items.map(fn).join("");
};
const createRow = (y) => {
const items = joinMap(interval(11), createItem(y));
return "<div class='row'>" + items + "</div>";
};
let rows = joinMap(interval(11), createRow);
html(first("main"), rows);
const playerPos = {
x: 1,
y: 1,
};
const renderLabyrinth = () => {
all(".item").forEach((it) => {
const pos = it.dataset.pos;
classes(it, {
filled: labyrinth.includes(pos),
player: pos === "" + playerPos.x + ":" + playerPos.y,
});
});
};
const move = (dx, dy) => () => {
const newPos = {
x: playerPos.x + dx,
y: playerPos.y + dy,
};
const pos = "" + newPos.x + ":" + newPos.y;
if (!labyrinth.includes(pos)) {
playerPos.x = newPos.x;
playerPos.y = newPos.y;
renderLabyrinth();
}
};
renderLabyrinth();
[
{ id: "#arrow-right", dir: move(1, 0) },
{ id: "#arrow-left", dir: move(-1, 0) },
{ id: "#arrow-down", dir: move(0, 1) },
{ id: "#arrow-up", dir: move(0, -1) },
].forEach(({ id, dir }) => on(first(id), "click")(dir));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment