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'; import { manualPan } from 'pan-zoom'; let svg, placing = []; 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()); const gb = svg.querySelector('.gameboard'); // TODO check if counter is on board before calling manualPan(gb, counter); 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(); } } export function start(el) { svg = el; 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(); }); svg.addEventListener('pointerover', e => { const targetCell = e.target.closest('[data-q][data-r][data-s][data-t], .frontmost'); // 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(); } //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 => { if (child.classList.contains('counter')) firingArc.get(svg, child).forEach(el => el.remove()); frontmostStore.delete(child); child.remove(); }); } }); 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 = 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(); } // debug // // Add a trooper counter //const defender = { dataset: { allegiance: 'defender', number: 1, squad: 2 }}; //const cell2 = getCell(-5, 10, -5, 0); //frontmost.setAttributeNS(null, 'transform', cell2.getAttributeNS(null, 'transform')); //const trooper2 = soldier.createCounter(defender, 'gl'); //frontmostStore.set(trooper2, cell2); //frontmost.append(trooper2); //cell2.classList.add('hover'); // const trooper1 = soldier.createCounter({ dataset: { allegiance: 'attacker', number: 1, squad: 1 }}, 'blazer'); soldier.place(svg, trooper1, getCell(-3, 9, -6, 0)); soldier.place( svg, soldier.createCounter({ dataset: { allegiance: 'defender', number: 1, squad: 1 }}, 'blazer'), getCell(1, -8, 7, 0) ); const t1Rect = trooper1.getBoundingClientRect(); setTimeout(() => { const t1Rect = trooper1.getBoundingClientRect(); console.log('trooper', trooper1, trooper1.getBoundingClientRect()); }, 10); // 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)) { 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); }