Web Dev Solutions

Catalin Mititiuc

import * as firingArc from './game/firing_arc.js'; import * as sightLine from './game/sight_line.js'; import * as soldier from './game/soldier.js'; import { Observable } from "./observable"; let svg, placing = []; const top = { collection: new Map() }; const frontmostStore = new Map(); function getCellContents(cell) { return cell.querySelectorAll('*:not(use[href="#hex"])'); } function getGridIndex({ parentElement: { dataset: { q, r, s, t }}}) { return { q: +q, r: +r, s: +s, t: +t }; } function getHex(cell) { return cell.querySelector('use[href="#hex"]'); } function getCellOccupant(cell) { return cell.querySelector('.counter') || svg.querySelector('.grid-top .counter'); } function getCells(svg) { return svg.querySelectorAll('[data-q][data-r][data-s][data-t]'); } function getLockedSightLine(svg) { return svg.querySelector('line.sight-line:not(.active)'); } function getActiveSightLine(svg) { return svg.querySelector('line.sight-line.active'); } function isCounter(el) { const regex = new RegExp('^#counter-') return el && regex.test(el.getAttribute('href')); } function isMechTemplate(el) { return el && el.getAttribute('class') === 'mech-template'; } function isClone(counter) { const isClone = counter.classList.contains('clone'), { allegiance: clAl, number: clNum } = counter.dataset; return { of: function ({ dataset: { allegiance, number }}) { return isClone && clAl == allegiance && clNum == number; } }; } function getCellPosition(cell) { const [x, y] = cell.getAttributeNS(null, 'transform').match(/-?\d+\.?\d*/g); return { x, y }; } function getCell(q, r, s, t) { return svg.querySelector(`g[data-q="${q}"][data-r="${r}"][data-s="${s}"][data-t="${t}"]`); } function getCounterAtGridIndex(...coords) { return getCell(...coords).querySelector('.counter'); } function getSelected() { return svg.querySelector(`.counter.selected[data-allegiance][data-number]`); } function deselect() { const selected = getSelected(); placing = []; if (selected) { selected.classList.remove(soldier.getSelectedClass()); clearSightLine(); firingArc.clipAll(svg); } } function clearSightLine() { sightLine.setHexes([]); sightLine.clear(); Observable.notify('distance'); } function calcSightLineIndexes(source, target) { const { q: sq, r: sr, s: ss } = source.dataset; const { q: tq, r: tr, s: ts } = target.dataset; const sourceIndex = { q: +sq, r: +sr, s: +ss }; const targetIndex = { q: +tq, r: +tr, s: +ts }; return sightLine.calcIndexes(sourceIndex, targetIndex); } function getSightLineHexes(indexes) { const selector = indexes .map(({ q, r, s }) => `g[data-q="${q}"][data-r="${r}"][data-s="${s}"] use[href="#hex"]`) .join(', '); return svg.querySelectorAll(selector); } function calcSightLine(source, target) { const indexes = calcSightLineIndexes(source, target); const hexes = getSightLineHexes(indexes); sightLine.setHexes(hexes); Observable.notify('distance', indexes.length - 1); } function updateSightLine(cell) { calcSightLine(cell, sightLine.getLockTarget()); sightLine.update(getCellPosition(cell)); } function drawSightLine(sourceCell, targetCell) { calcSightLine(sourceCell, targetCell); const line = sightLine.create(getCellPosition(sourceCell), getCellPosition(targetCell)); svg.querySelector('.gameboard').appendChild(line); } function moveBackOneStepInHistory(counter) { const trace = soldier.getTrace(svg, counter); counter.remove(); counter = getCounterAtGridIndex(...counter.dataset.previous.split(',')); counter.classList.remove('clone'); counter.classList.add(soldier.getSelectedClass()); if (!('previous' in counter.dataset)) { trace.remove(); } else { const points = trace.getAttribute('points').split(' '); points.pop(); trace.setAttributeNS(null, 'points', points.join(' ')); } return counter; } function clearMoveHistory(clone, counter) { clone.classList.remove('clone'); clone.classList.add(soldier.getSelectedClass()); counter.remove(); counter = clone; soldier.removeClones(svg, counter); soldier.getTrace(svg, counter).remove(); return counter; } function deleteClone(occupant, counter, cell) { const index = getGridIndex(occupant), trace = soldier.getTrace(svg, counter), pos = getCellPosition(cell), points = trace.getAttribute('points').split(' ').filter(p => p != `${pos.x},${pos.y}`).join(' ');; let current = counter; trace.setAttributeNS(null, 'points', points); while (current.dataset.previous != `${index.q},${index.r},${index.s},${index.t}`) { current = getCounterAtGridIndex(...current.dataset.previous.split(',')); } current.dataset.previous = occupant.dataset.previous; occupant.remove(); } function hasPreviousMoveInHistory(counter) { return 'previous' in counter.dataset; } function selectOffBoard() { Observable.notify('select', this); } function select(data) { const counter = data && (soldier.getCounter(svg, data) || soldier.createCounter(data)); const isSelected = data && data.classList && data.classList.contains('selected'); deselect(); if (isSelected || !data) return; counter.classList.add(soldier.getSelectedClass()); firingArc.get(svg, counter).forEach(el => el.removeAttribute('clip-path')); placing.push(counter); } function endMove() { const selected = getSelected(); if (selected) { soldier.endMove(svg, selected); deselect(); } } // Work around webkit bug https://bugs.webkit.org/show_bug.cgi?id=233432 function workaroundForWebKitBug233432(listener) { return e => { const elUnderCursor = svg.parentNode.elementFromPoint(e.clientX, e.clientY); if (!e.target.contains(elUnderCursor)) listener(e); }; } export function start(el) { svg = el; //const gridTop = svg.querySelector('.grid-top'); //top.container = svg.querySelector('.grid-top > .container'); //const topHex = svg.querySelector('.grid-top > use[href="#hex"]'); const grid = svg.querySelector('.grid'); const frontmost = grid.querySelector('.frontmost'); // For when the pointer leaves the window document.querySelector('object').addEventListener('pointerout', e => { if (clearHexDialog.open) return; console.log('object pointerout'); console.log('Left map... CLEARING HOVERS'); svg.querySelectorAll('.hover').forEach(el => el.classList.remove('hover')); [...frontmost.children].forEach(child => { const parent = frontmostStore.get(child); parent.append(child); if (child.classList.contains('counter')) { firingArc.toggleCounterVisibility(svg, child, false); } frontmostStore.delete(child); }); getActiveSightLine(svg) && clearSightLine(); console.log('object', svg.querySelectorAll('.hover')); }); svg.addEventListener('pointerover', e => { const targetCell = e.target.closest('[data-q][data-r][data-s][data-t], .frontmost'); console.log( 'SVG pointerOVER ================================', '\ne.target', e.target, '\ntarget closest', targetCell, '\ne.relatedTarget', e.relatedTarget, '\nrelatedTarget closest', e.relatedTarget && e.relatedTarget.closest('[data-q][data-r][data-s][data-t]') ); //console.log('target closest root', e.target.closest('[data-q][data-r][data-s][data-t] > *')); // Pointer moves outside the edge of the grid if (!targetCell) { console.log('No target cell... CLEARING HOVERS'); svg.querySelectorAll('.hover').forEach(el => el.classList.remove('hover')); [...frontmost.children].forEach(child => { const parent = frontmostStore.get(child); parent.append(child); if (child.classList.contains('counter')) { firingArc.toggleCounterVisibility(svg, child, false); } frontmostStore.delete(child); }); } // Pointer moves over a cell if (targetCell) { if ([ // that is not already highlighted !targetCell.classList.contains('hover'), // 's contents that is in frontmost, whose parent cell is not already highlighted !(targetCell.classList.contains('frontmost') && frontmostStore.get(e.target.closest('.frontmost > *')).classList.contains('hover')) ].every(e => e)) { console.log('Target cell missing hover... CLEARING HOVERS AND ADDING TO TARGET CELL'); svg.querySelectorAll('.hover').forEach(el => el.classList.remove('hover')); if (placing[0]?.getAttributeNS(null, 'class') === 'mech-template') { targetCell.prepend(placing[0]); } [...frontmost.children].forEach(child => { const parent = frontmostStore.get(child); parent.append(child); if (child.classList.contains('counter')) { firingArc.toggleCounterVisibility(svg, child, false); } frontmostStore.delete(child); }); frontmost.setAttributeNS(null, 'transform', targetCell.getAttributeNS(null, 'transform')); const children = [...targetCell.children].filter(c => c.getAttributeNS(null, 'href') !== '#hex'); if (children.length > 0) { children.forEach(child => { if (child.classList.contains('counter')) { firingArc.toggleCounterVisibility(svg, child, true); } frontmostStore.set(child, targetCell); frontmost.append(child); }); } targetCell.classList.contains('frontmost') ? frontmostStore.get(e.target.closest('.frontmost > *')).classList.add('hover') : targetCell.classList.add('hover'); } } const selected = getSelected(); if (selected && targetCell && svg.querySelector('.grid').contains(selected) && !getLockedSightLine(svg) && selected.parentElement !== frontmost) { clearSightLine(); drawSightLine(selected.parentElement, grid.querySelector('.hover')); } else { getActiveSightLine(svg) && clearSightLine(); } //const counter = targetCell && targetCell.querySelector('.counter'); //console.log('pointerover', 'targetCell', targetCell); //if (targetCell) { // const children = [...targetCell.children].filter(c => c.getAttributeNS(null, 'href') !== '#hex'); // if (children.length > 0) { // frontmost.setAttributeNS(null, 'transform', targetCell.getAttributeNS(null, 'transform')); // children.forEach(child => { // if (child.classList.contains('counter')) { // firingArc.toggleCounterVisibility(svg, child, true); // } // frontmostStore.set(child, targetCell); // frontmost.append(child); // }); // } //} //if (counter) { // firingArc.toggleCounterVisibility(svg, counter, true); // frontmost.setAttributeNS(null, 'transform', targetCell.getAttributeNS(null, 'transform')); // frontmostStore.set(counter, targetCell); // frontmost.append(counter); //} //targetCell && targetCell.classList.add('hover'); //if (targetCell && !targetCell.classList.contains('frontmost')) { // targetCell.classList.add('hover'); // const occupant = targetCell.querySelector('.counter'); // // if (occupant) { // firingArc.toggleCounterVisibility(svg, occupant, true); // } // const children = [...targetCell.children].filter(c => c.getAttributeNS(null, 'href') !== '#hex'); // if (children.length > 0) { // frontmost.setAttributeNS(null, 'transform', targetCell.getAttributeNS(null, 'transform')); // children.forEach(child => { // frontmostStore.set(child, targetCell); // frontmost.append(child); // }); // } //} console.log('frontmost contents', frontmost.children); }); //svg.addEventListener('pointerout', e => { // //console.log('pointer out target', e.target); // const targetCell = e.target.closest('[data-q][data-r][data-s][data-t], .frontmost'); // console.log('SVG pointerOUT', 'e.target', e.target, 'relatedTarget', e.relatedTarget, 'closest', targetCell); // // if (targetCell) { // //console.log('SVG pointerout', targetCell); // [...frontmost.children].forEach(child => { // //console.log('child', child, 'relatedTarget', e.relatedTarget); // //if ([ // // !e.relatedTarget, // out of the window // // targetCell.classList.contains('frontmost') && !e.relatedTarget.closest('.frontmost'), // from one element in frontmost to another element in frontmost // // !targetCell.classList.contains('frontmost') && frontmostStore.get(child) === targetCell, // leaving from a hex under frontmost // //].some(e => e)) { // console.log('child', child, 'belongs to', frontmostStore.get(child)); // //console.log('relatedTarget', e.relatedTarget); // //if (!e.relatedTarget || frontmostStore.get(child) !== targetCell || (e.relatedTarget !== child && !child.contains(e.relatedTarget))) { // //if (!e.relatedTarget || frontmostStore.get(child) !== targetCell || e.relatedTarget !== child) { // const closest = e.relatedTarget && e.relatedTarget.closest('[data-q][data-r][data-s][data-t], .frontmost'); // if (!e.relatedTarget || (closest && !closest.classList.contains('hover') && !closest.classList.contains('frontmost'))) { // const parent = frontmostStore.get(child); // console.log('returning to', parent); // parent.append(child); // firingArc.toggleCounterVisibility(svg, child, false); // parent.classList.remove('hover'); // frontmostStore.delete(child); // } // }); // if (frontmost.children.length < 1) targetCell.classList.remove('hover'); // } else { // [...frontmost.children].forEach(child => { // const parent = frontmostStore.get(child); // parent.append(child); // parent.classList.remove('hover'); // firingArc.toggleCounterVisibility(svg, child, false); // frontmostStore.delete(child); // }); // } // console.log('hover cells', svg.querySelectorAll('.hover')); // console.log('frontmost contents', frontmost.children); //}); grid.addEventListener('click', clickHandler); const clearHexDialog = document.querySelector('#clear-hex'); clearHexDialog.addEventListener('close', e => { if (clearHexDialog.returnValue === 'confirm') { [...frontmost.children].forEach(child => { frontmostStore.delete(child); child.remove(); }); } }); //gridTop.addEventListener('pointerleave', workaroundForWebKitBug233432(e => { // console.log('pointerleave top', performance.now(), top.cell); // const occupant = svg.querySelector('.grid-top .container .counter'); // // if (occupant) { // firingArc.toggleCounterVisibility(svg, occupant, false); // } // // [...top.container.children].forEach(child => { // top.collection.get(child).parent.append(child); // top.collection.delete(child); // }); // // top.cell = null; // // getActiveSightLine(svg) && clearSightLine(); //})); //topHex.addEventListener('click', clickHandler); grid.addEventListener('contextmenu', e => { e.preventDefault(); const selected = getSelected(); if (selected) { if (sightLine.getSightLine()) sightLine.toggleLock(grid.querySelector('.hover')); if (getActiveSightLine(svg)) { clearSightLine(); if (selected.parentElement !== frontmost) drawSightLine(selected.parentElement, grid.querySelector('.hover')); } } else { clearHexDialog.showModal(); } }); const startingLocations = svg.querySelector('.start-locations'); startingLocations && getUnits(startingLocations).forEach(unit => unit.addEventListener('click', selectOffBoard)); function clickHandler(e) { //const targetCell = e.target.closest('[data-q][data-r][data-s][data-t]') || frontmostStore.get(e.target.closest('.frontmost > *')); const targetCell = grid.querySelector('.hover'); const occupant = frontmost.querySelector('.counter'); let toPlace = placing.pop(); if (isCounter(toPlace) || isMechTemplate(toPlace)) { frontmostStore.set(toPlace, targetCell); isMechTemplate(toPlace) ? frontmost.prepend(toPlace) : frontmost.append(toPlace); if (isCounter(toPlace)) arrangeCounters(frontmost); removeEventListener("keydown", handleMechTemplateRotation); } else if (toPlace && !occupant) { frontmostStore.set(toPlace, targetCell); const mechTemplate = frontmost.querySelector('.mech-template'); mechTemplate ? mechTemplate.after(toPlace) : frontmost.prepend(toPlace); placing.push(toPlace); getLockedSightLine(svg) ? updateSightLine(targetCell) : clearSightLine(); } else if (toPlace && occupant) { if (toPlace === occupant) { Observable.notify('select'); } else { Observable.notify('select', occupant); } } else if (!toPlace && occupant) { Observable.notify('select', occupant); } const selected = getSelected(); } //getCells(svg).forEach(cell => { // cell.addEventListener('pointerleave', () => { // console.log('pointerleave cell', performance.now(), cell); // }); // // cell.addEventListener('pointerover', () => { // console.log('pointerenter', performance.now(), cell); // // top.cell = cell; // // [...top.container.children].forEach(child => { // top.collection.get(child).parent.append(child); // top.collection.delete(child); // }); // // top.container.parentElement.setAttributeNS(null, 'transform', cell.getAttributeNS(null, 'transform')); // // [...cell.children].filter(c => c.getAttributeNS(null, 'href') !== '#hex').forEach(child => { // top.collection.set(child, { parent: cell }); // top.container.append(child); // }); // // let occupant = svg.querySelector('.grid-top .container .counter'); // const selected = getSelected(); // // if (placing[0]?.getAttributeNS(null, 'class') == 'mech-template') { // cell.appendChild(placing[0]); // } // // if (selected && svg.querySelector('.grid').contains(selected) && !getLockedSightLine(svg) && cell !== selected.parentElement) { // clearSightLine(); // drawSightLine(selected.parentElement, cell); // } // // occupant = getCellOccupant(cell); // // if (occupant) { // firingArc.toggleCounterVisibility(svg, occupant, true); // } // }); //}); //const cell = document.querySelector('[data-q="0"][data-r="0"][data-s="0"][data-t="0"]'); //const povr = new PointerEvent('pointerover'); //const pout = new PointerEvent('pointerout'); //cell.dispatchEvent(povr); //cell.dispatchEvent(pout); // debug // // Add a trooper counter //const defender = { dataset: { allegiance: 'defender', number: 1, squad: 2 }}; //const cell2 = getCell(-1, 0, 1, 0); //frontmost.setAttributeNS(null, 'transform', cell2.getAttributeNS(null, 'transform')); //const trooper2 = soldier.createCounter(defender, 'blazer'); //frontmostStore.set(trooper2, cell2); //frontmost.append(trooper2); //cell2.classList.add('hover'); // //const cell = getCell(0, 0, 0, 0); //const attacker = { dataset: { allegiance: 'attacker', number: 1, squad: 1 }}; //const trooper = soldier.createCounter(attacker, 'blazer'); //soldier.place(svg, trooper, cell); // Add some counters in an unoccupied cell //const countersCell = getCell(-1, 1, 0, 0); //const counter = document.createElementNS(svgns, 'use'); //const name = 'grenade'; //counter.setAttributeNS(null, 'href', `#counter-${name}`); //counter.classList.add(`counter-${name}`); //frontmostStore.set(counter, cell2); //frontmost.append(counter); //arrangeCounters(frontmost) //counter.addEventListener('click', e => { // e.stopPropagation() // const container = counter.parentElement; // counter.remove() // arrangeCounters(container); //}); //setCounter('grenade'); //setCounter('prone'); //setCounter('1st-floor'); //const e = new PointerEvent('click'); //countersCell.dispatchEvent(e); //countersCell.dispatchEvent(e); //countersCell.dispatchEvent(e); /////////// Observable.subscribe('select', select); Observable.subscribe('endmove', endMove); console.log('gameboard.js loaded'); } export function stop() { Observable.unsubscribe('select', select); Observable.unsubscribe('endmove', endMove); } export function getUnits() { return soldier.getAllCounters(svg); } export function clearFiringArcs(allegiance) { firingArc.clear(svg, allegiance); } export function toggleFiringArcVisibility() { firingArc.toggleVisibility(svg, this.dataset.allegiance); } export function setFiringArc() { const counter = getSelected(), isOnBoard = counter => counter && counter.parentElement.hasAttribute('data-q'); if (isOnBoard(counter)) { //returnToParent(top); firingArc.set(svg, this.dataset.size, counter, getCellPosition(counter.parentElement)); } } export function setCounter(name) { const selected = getSelected(); const counter = document.createElementNS(svgns, 'use'); counter.addEventListener('click', e => { e.stopPropagation() const container = counter.parentElement; counter.remove() arrangeCounters(container); }); counter.setAttributeNS(null, 'href', `#counter-${name}`); counter.classList.add(`counter-${name}`); if (selected) { selected.append(counter); arrangeCounters(selected); } else placing.push(counter); } function arrangeCounters(container) { const counters = [...container.children].filter(isCounter); const length = 12; const gravity = 1; const lateralForce = gravity; const rads = Math.atan(lateralForce / gravity); const bestFitCount = 8; const deflection = counters.length > bestFitCount ? 2 * Math.PI / counters.length : Math.atan(lateralForce / gravity); counters.forEach((counter, index, arr) => { const mult = index - arr.length / 2 + 0.5; const theta = deflection * mult; const x = length * Math.sin(theta); const y = length * Math.cos(theta); counter.setAttributeNS(null, 'style', `--x: ${-x}px; --y: ${y}px`); }); } function handleMechTemplateRotation(event) { const counter = placing[0]; const upper = placing[0].querySelector('use[href="#mech-template-upper"]'); if (event.key === 'a') { let direction = +counter.style.transform.match(/-?\d+/) || 0; direction -= 60; counter.style.transform = `rotate(${direction}deg)`; } else if (event.key === 'd') { let direction = +counter.style.transform.match(/-?\d+/) || 0; direction += 60; counter.style.transform = `rotate(${direction}deg)`; } else if (event.key === 'q') { let facing = +upper.style.transform.match(/-?\d+/) || 0; facing = facing <= -60 ? -60 : facing - 60; upper.style.transform = `rotate(${facing}deg)`; } else if (event.key === 'e') { let facing = +upper.style.transform.match(/-?\d+/) || 0; facing = facing >= 60 ? 60 : facing + 60; upper.style.transform = `rotate(${facing}deg)`; } } export function setMechTemplate() { const counter = document.createElementNS(svgns, 'g'); counter.setAttributeNS(null, 'class', 'mech-template'); counter.style.pointerEvents = 'none'; counter.style.transition = 'transform 0.5s'; const lower = document.createElementNS(svgns, 'use'); lower.setAttributeNS(null, 'href', '#mech-template-lower'); const upper = document.createElementNS(svgns, 'use'); upper.setAttributeNS(null, 'href', '#mech-template-upper'); upper.style.transition = 'transform 0.5s'; counter.appendChild(lower); counter.appendChild(upper); addEventListener("keydown", handleMechTemplateRotation); placing.push(counter); }