Web Dev Solutions

Catalin Mititiuc

From 460027e96507c8015878a03f14508bd50d68e97f Mon Sep 17 00:00:00 2001 From: Catalin Mititiuc Date: Tue, 16 Apr 2024 19:41:27 -0700 Subject: Move most game logic into its own file --- src/index.js | 1030 ++------------------------------------------------- src/modules/game.js | 906 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 944 insertions(+), 992 deletions(-) create mode 100644 src/modules/game.js (limited to 'src') diff --git a/src/index.js b/src/index.js index 4a66c76..a0a99f4 100644 --- a/src/index.js +++ b/src/index.js @@ -1,135 +1,5 @@ import { pan, zoom } from 'svg-pan-zoom'; - -function isEven(n) { - return n % 2 === 0; -} - -function radToDeg(radians) { - return radians * 180 / Math.PI; -} - -function calculateAngle(xDiff, yDiff) { - yDiff = -yDiff; - let angle = Math.abs(Math.atan(yDiff / xDiff)); - - if (xDiff < 0 && yDiff > 0) { - angle = Math.PI - angle; - } else if (xDiff < 0 && yDiff < 0) { - angle = Math.PI + angle; - } else if (xDiff > 0 && yDiff < 0) { - angle = 2 * Math.PI - angle; - } - - return angle; -} - -function edgePoint(x1, y1, x2, y2, maxX, maxY) { - let pointCoords, - xDiff = x2 - x1, - yDiff = y2 - y1, - xIntercept = y => (y - y1) * xDiff / yDiff + x1, - yIntercept = x => (x - x1) * yDiff / xDiff + y1; - - if (xDiff > 0 && yDiff > 0) { - let x = xIntercept(maxY); - - pointCoords = x <= maxX ? [x, maxY] : [maxX, yIntercept(maxX)]; - } else if (xDiff > 0 && yDiff < 0) { - let y = yIntercept(maxX); - - pointCoords = y >= 0 ? [maxX, y] : [xIntercept(0), 0]; - } else if (xDiff < 0 && yDiff < 0) { - let x = xIntercept(0); - - pointCoords = x >= 0 ? [x, 0] : [0, yIntercept(0)]; - } else { - let y = yIntercept(0); - - pointCoords = y <= maxY ? [0, y] : [xIntercept(maxY), maxY]; - } - - return pointCoords; -} - -function evenr_to_axial(x, y) { - return { q: x - (y + (y & 1)) / 2, r: y }; -} - -function axial_to_evenr(q, r) { - return { x: q + (r + (r & 1)) / 2, y: r }; -} - -function axial_distance(q1, r1, q2, r2) { - return (Math.abs(q1 - q2) + Math.abs(q1 + r1 - q2 - r2) + Math.abs(r1 - r2)) / 2; -} - -function offset_distance(x1, y1, x2, y2) { - let { q: q1, r: r1 } = evenr_to_axial(x1, y1), - { q: q2, r: r2 } = evenr_to_axial(x2, y2); - - return axial_distance(q1, r1, q2, r2); -} - -function cube_to_axial(q, r, s) { - return { q: q, r: r }; -} - -function axial_to_cube(q, r) { - return { q: q, r: r, s: -q - r }; -} - -function cube_round(q, r, s) { - rQ = Math.round(q); - rR = Math.round(r); - rS = Math.round(s); - - let q_diff = Math.abs(rQ - q), - r_diff = Math.abs(rR - r), - s_diff = Math.abs(rS - s); - - if (q_diff > r_diff && q_diff > s_diff) { - rQ = -rR - rS; - } else if (r_diff > s_diff) { - rR = -rQ - rS; - } else { - rS = -rQ - rR; - } - - return { q: rQ, r: rR, s: rS }; -} - -function axial_round(q, r) { - let cube = axial_to_cube(q, r), - round = cube_round(cube.q, cube.r, cube.s), - axial = cube_to_axial(round.q, round.r, round.s); - - return { q: axial.q, r: axial.r }; -} - -function lerp(a, b, t) { - return a + (b - a) * t; -} - -function axial_lerp(q1, r1, q2, r2, t) { - return { q: lerp(q1, q2, t), r: lerp(r1, r2, t) }; -} - -function linedraw(x1, y1, x2, y2) { - let axial1 = evenr_to_axial(x1, y1), - axial2 = evenr_to_axial(x2, y2), - n = offset_distance(x1, y1, x2, y2), - results = []; - - for (let i = 0; i <= n; i++) { - let lerp = axial_lerp(axial1.q, axial1.r, axial2.q, axial2.r, 1.0 / n * i), - round = axial_round(lerp.q, lerp.r), - { x, y } = axial_to_evenr(round.q, round.r); - - results.push([x, y]); - } - - return results; -} +import Game from './modules/game.js'; const PanZoom = new function () { const vb = 'viewBox'; @@ -171,858 +41,50 @@ const PanZoom = new function () { }; }; -class Game { - constructor(svg) { - this.svg = svg; - - this.setUpSightLine(this); - this.setUpCounter(this); - this.setUpRecordSheet(); - this.setUpCells(); - } - - static HORZ_POINT_DISTANCE = 1.005; - static VERT_POINT_DISTANCE = Math.sqrt(3) * Game.HORZ_POINT_DISTANCE / 2; - - static FIRING_ARC_SIZE = { - 'small': Math.atan(Game.HORZ_POINT_DISTANCE / (6 * Game.VERT_POINT_DISTANCE)), - 'medium': Math.atan((Game.HORZ_POINT_DISTANCE / 2) / Game.VERT_POINT_DISTANCE), - 'large': Math.atan((21 * Game.HORZ_POINT_DISTANCE) / (6 * Game.VERT_POINT_DISTANCE)) - }; - - #positionFiringArc(e) { - let activeFiringArc = this.querySelector('polygon.firing-arc.active'); - - // TODO: handle exactly horizontal and vertical lines - - if (activeFiringArc) { - let activeFiringArcOutline = this.querySelector(`#lines polygon[data-troop-number="${activeFiringArc.dataset.troopNumber}"][data-troop-allegiance="${activeFiringArc.dataset.troopAllegiance}"]`), - board = this.querySelector('#image-maps'), - { width, height } = board.getBBox(), - pt = new DOMPoint(e.clientX, e.clientY), - { x: pointerX, y: pointerY } = pt.matrixTransform(board.getScreenCTM().inverse()), - [maxXpx, maxYpx] = [width, height], - { x: x1px, y: y1px } = activeFiringArc.points[0]; - - let [x2px, y2px] = [ - pointerX / width * maxXpx, - pointerY / height * maxYpx - ]; - - let xDiff = x2px - x1px; - let yDiff = y2px - y1px; - let angle = calculateAngle(xDiff, yDiff); - - let arcAngle = Game.FIRING_ARC_SIZE[activeFiringArc.dataset.size]; - let distance = Math.sqrt((x2px - x1px) ** 2 + (y2px - y1px) ** 2); - let yDelta = distance * Math.cos(angle) * Math.tan(arcAngle); - let xDelta = distance * Math.sin(angle) * Math.tan(arcAngle); - - let [newY1, newX1] = [y2px + yDelta, x2px + xDelta]; - let [newY2, newX2] = [y2px - yDelta, x2px - xDelta]; - - [newX1, newY1] = edgePoint(x1px, y1px, newX1, newY1, maxXpx, maxYpx); - [newX2, newY2] = edgePoint(x1px, y1px, newX2, newY2, maxXpx, maxYpx); - - let oppositeEdgeConditions = [ - newX1 == 0 && newX2 == maxXpx, - newX2 == 0 && newX1 == maxXpx, - newY1 == 0 && newY2 == maxYpx, - newY2 == 0 && newY1 == maxYpx - ] - - let orthogonalEdgeConditions = [ - (newX1 == 0 || newX1 == maxXpx) && (newY2 == 0 || newY2 == maxYpx), - (newX2 == 0 || newX2 == maxXpx) && (newY1 == 0 || newY1 == maxYpx), - ] +const RecordSheet = new function () { + this.unSelect = function () { + let selected = this.getSelected(); - let points; - - if (oppositeEdgeConditions.some(e => e)) { - let cornerPoints; - - if (xDiff > 0 && yDiff > 0) { - if ((newY1 == 0 && newY2 == maxYpx) || (newY1 == maxYpx && newY2 == 0)) { - cornerPoints = [[maxXpx, 0], [maxXpx, maxYpx]]; - } else { - cornerPoints = [[maxXpx, maxYpx], [0, maxYpx]]; - } - } else if (xDiff > 0 && yDiff < 0) { - if ((newY1 == 0 && newY2 == maxYpx) || (newY1 == maxYpx && newY2 == 0)) { - cornerPoints = [[maxXpx, 0], [maxXpx, maxYpx]]; - } else { - cornerPoints = [[0, 0], [maxXpx, 0]]; - } - - } else if (xDiff < 0 && yDiff > 0) { - if ((newY1 == 0 && newY2 == maxYpx) || (newY1 == maxYpx && newY2 == 0)) { - cornerPoints = [[0, maxYpx], [0, 0]]; - } else { - cornerPoints = [[maxXpx, maxYpx], [0, maxYpx]]; - } - - } else { - if ((newY1 == 0 && newY2 == maxYpx) || (newY1 == maxYpx && newY2 == 0)) { - cornerPoints = [[0, maxYpx], [0, 0]]; - } else { - cornerPoints = [[0, 0], [maxXpx, 0]]; - } - - } - points = `${x1px},${y1px} ${newX1},${newY1} ${cornerPoints[1]} ${cornerPoints[0]} ${newX2},${newY2}`; - } else if (orthogonalEdgeConditions.some(e => e)) { - let cornerPoints = []; - let cp1, cp2; - - if (newX1 == 0 || newX1 == maxXpx) { - cp1 = [newX1, yDiff > 0 ? maxYpx : 0]; - } else { - cp1 = [xDiff > 0 ? maxXpx : 0, newY1]; - } - - if (newX2 == 0 || newX2 == maxXpx) { - cp2 = [newX2, yDiff > 0 ? maxYpx : 0]; - } else { - cp2 = [xDiff > 0 ? maxXpx : 0, newY2]; - } - - if (cp1[0] == cp2[0] && cp1[1] == cp2[1]) { - cornerPoints.push(cp1); - } else { - cornerPoints.push(cp1); - cornerPoints.push([xDiff > 0 ? maxXpx : 0, yDiff > 0 ? maxYpx : 0]) - cornerPoints.push(cp2); - } - - points = `${x1px},${y1px} ${newX1},${newY1} ${cornerPoints.join(' ')} ${newX2},${newY2}`; - } else { - points = `${x1px},${y1px} ${newX1},${newY1} ${newX2},${newY2}`; - } - - activeFiringArcOutline.setAttributeNS(null, 'points', points); - activeFiringArc.setAttributeNS(null, 'points', points); + if (selected) { + selected.classList.remove('selected'); + document.getElementById('toggle-prone-counter').checked = false; } - } - - getCells() { - return this.svg.querySelectorAll('g[data-x]'); - } - - getCell(x, y) { - return this.svg.querySelector(`g[data-y="${y}"] g[data-x="${x}"]`); - } - - getHex(cell) { - return cell.querySelector('use[href="#hex"]'); - } - - getCounters() { - return this.svg.querySelectorAll(`use[data-allegiance][data-number]:not(.clone)`); - } - - getCounter(al, n) { - return this.svg.querySelector(`use[data-allegiance="${al}"][data-number="${n}"]:not(.clone)`); - } - - getCounterAndClones(al, n) { - return this.svg.querySelectorAll(`use[data-allegiance="${al}"][data-number="${n}"]`); - } - - getClones(al, n) { - return this.svg.querySelectorAll(`use[data-allegiance="${al}"][data-number="${n}"].clone`); - } - - getSelected() { - return this.svg.querySelector(`use[data-allegiance][data-number].selected`); - } - - getSightLine() { - return this.svg.querySelector('line.sight-line'); - } - - getExistingArcs(al, n) { - return this.svg.querySelectorAll(`#firing-arcs polygon[data-troop-number="${n}"][data-troop-allegiance="${al}"]`); - } - - getUnclippedFiringArcs() { - return this.svg.querySelectorAll('#firing-arcs polygon:not([clip-path])'); - } - - getGridIndex({ parentElement }) { - return { x: parentElement.dataset.x, y: parentElement.parentElement.dataset.y }; - } - - getBoard() { - return this.svg.querySelector('.board'); - } - - getActiveHexes() { - return this.svg.querySelectorAll('use[href="#hex"].active'); - } - - getCellPosition(cell) { - let pt = new DOMPoint(0, 0), - transform = getComputedStyle(cell).transform.match(/-?\d+\.?\d*/g), - mtx = new DOMMatrix(transform); - pt = pt.matrixTransform(mtx); - - transform = getComputedStyle(cell.parentElement).transform.match(/-?\d+\.?\d*/g); - mtx = new DOMMatrix(transform); - pt = pt.matrixTransform(mtx); - - return pt; - } - - setUpCells() { - this.getCells().forEach(cell => { - let group = cell, - point = this.getHex(cell); - - group.addEventListener('click', e => { - let cl = e.target.classList, - sl = this.getSightLine(), - targetIsSomeOtherUnitCounter = cl.contains('counter') && !cl.contains('clone'), - selected = this.RecordSheet.getSelected(); - - // maybe we should start with, "are we clicking on a counter?" - if (sl) { - let { troopNumber: sTn, troopAllegiance: sTa } = selected.dataset, - { troopNumber: tTn, troopAllegiance: tTa } = e.target.dataset, - sightLineInLockedPosition = !sl.classList.contains('active'), - targetIsCounterOrCloneOfSelected = cl.contains('counter') && sTn == tTn && sTa == tTa; - - if (sightLineInLockedPosition && targetIsCounterOrCloneOfSelected) { - let counterParent = Counter.get(tTn, tTa).parentElement, - [x, y] = counterParent.getAttribute('transform').match(/-?\d+\.?\d*/g), - target = ptGrp.querySelector(`g[transform="translate(${sl.getAttribute('x2')} ${sl.getAttribute('y2')})"]`), - { x: x1, y: y1 } = counterParent.dataset, - { x: x2, y: y2 } = target.dataset; - - sl.setAttributeNS(null, 'x1', x); - sl.setAttributeNS(null, 'y1', y); - - SightLine.drawHexes(...[x1, y1, x2, y2].map(n => parseInt(n))); - } else if (targetIsCounterOrCloneOfSelected || targetIsSomeOtherUnitCounter) { - if (targetIsSomeOtherUnitCounter) { - RecordSheet.select(e.target); - Counter.select(e.target); - } - - SightLine.clear(); - } - } else if (targetIsSomeOtherUnitCounter) { - this.RecordSheet.select(e.target); - this.Counter.select(e.target); - } - }); - - point.addEventListener('click', e => { - let selectedSoldier = document.querySelector('.soldier-record.selected'); - let existingOccupant = - this.svg.querySelector(`.counter[data-x="${point.dataset.x}"][data-y="${point.dataset.y}"]`); - - if (selectedSoldier && !existingOccupant) { - let sl = this.svg.querySelector('.sight-line'); - - this.Counter.place(selectedSoldier, point); - - if (sl) { - if (sl.classList.contains('active')) { - this.SightLine.clear(); - } else { - let { x, y } = this.getCellPosition(point.parentElement), - target = this.svg.querySelector(`use[href="#hex"].sight-line-target`), - { x: x2, y: y2 } = this.getGridIndex(target), - { x: x1, y: y1 } = this.getGridIndex(point); - - sl.setAttributeNS(null, 'x1', x); - sl.setAttributeNS(null, 'y1', y); - - this.SightLine.drawHexes(...[x1, y1, x2, y2].map(n => parseInt(n))); - } - } - } - }); - - group.addEventListener('contextmenu', e => { - e.preventDefault(); - let sl = this.svg.querySelector('.sight-line'); - - if (sl) { - sl.classList.toggle('active'); - - if (sl.classList.contains('active')) { - this.SightLine.clear(); - } else { - group.querySelector(`use[href="#hex"]`).classList.add('sight-line-target'); - } - - group.dispatchEvent(new MouseEvent('pointerover')); - } - }); - - group.addEventListener('pointerover', e => { - // group.classList.add('hover'); - - let selected = this.RecordSheet.getSelected(); - - if (selected) { - let { troopNumber: tn, troopAllegiance: ta } = selected.dataset, - counter = this.Counter.get(tn, ta), - sl = this.svg.querySelector('.sight-line'); - - if (counter && (!sl || sl.classList.contains('active'))) { - let sourceCell = counter.parentElement; - - if (sourceCell != group) { - this.SightLine.draw(sourceCell, group); - } - } - } - }); - - group.addEventListener('pointerout', e => { - let sl = this.svg.querySelector('.sight-line.active'); - - if (sl && sl.classList.contains('active')) { - this.SightLine.clear(); - } - }); - }); - } - - setUpRecordSheet() { - const Counter = this.Counter, - svg = this; - - this.RecordSheet = new function () { - let clipUnclippedFiringArcs = function () { - let unclipped = svg.getUnclippedFiringArcs(); - - unclipped.forEach(el => { - let { troopNumber, troopAllegiance } = el.dataset, - clipPathId = `clip-path-${troopAllegiance}-${troopNumber}`; - - let isVisible = - document - .getElementById('toggle-firing-arc-vis') - .querySelector(`input[data-allegiance="${troopAllegiance}"]`) - .checked; - - if (isVisible) { - svg.svg.querySelector(`#${clipPathId}`).style.display = 'none'; - } - - el.setAttributeNS(null, 'clip-path', `url(#${clipPathId})`); - }); - }; - - this.unSelect = function () { - let selected = this.getSelected(); - - if (selected) { - selected.classList.remove('selected'); - document.getElementById('toggle-prone-counter').checked = false; - } - - clipUnclippedFiringArcs(); - Counter.unSelect(); - }; - - this.getSelected = function () { - return document.querySelector('.soldier-record.selected'); - }; - - this.select = function (el) { - let { number: troopNumber, allegiance: troopAllegiance } = el.dataset, - proneStatus = Counter.hasProne(troopNumber, troopAllegiance); - - this.unSelect(); - document.querySelector(`#record-sheet .soldier-record[data-troop-number="${troopNumber}"][data-troop-allegiance="${troopAllegiance}"]`).classList.add('selected'); - document.getElementById('toggle-prone-counter').checked = proneStatus; - let existingArcs = svg.getExistingArcs(troopAllegiance, troopNumber); - existingArcs.forEach(el => el.removeAttribute('clip-path')); - }; - }; - } - - setUpCounter(container) { - this.Counter = new function () { - let selectedClass = 'selected', - svgns = "http://www.w3.org/2000/svg", - - dataSelector = function (troopNumber, allegiance) { - return `[data-number="${troopNumber}"][data-allegiance="${allegiance}"]`; - }, - - selector = function (troopNumber, allegiance) { - return `use.counter${dataSelector(troopNumber, allegiance)}`; - }, - - position = function (x, y) { - return `g[data-x="${x}"][data-y="${y}"]`; - }, - - counterPosition = function (x, y) { - return `use.counter[data-x="${x}"][data-x="${y}"]`; - }, - - traceSelector = function (troopNumber, allegiance) { - return `polyline.move-trace${dataSelector(troopNumber, allegiance)}`; - }, - - clickClone = function (e) { - e.stopPropagation(); - - let { number: troopNumber, allegiance: troopAllegiance } = this.dataset, - pos = container.getCellPosition(this.parentElement); - - if (container.Counter.isSelected(troopNumber, troopAllegiance)) { - let trace = container.svg.querySelector(traceSelector(troopNumber, troopAllegiance)), - points = trace.getAttribute('points').split(' '); - - if (`${pos.x},${pos.y}` == points.at(0)) { - const counter = container.getCounter(troopAllegiance, troopNumber), - lockedSl = container.svg.querySelector('.sight-line:not(.active)'); - - counter.setAttributeNS(null, 'x', 0); - counter.setAttributeNS(null, 'y', 0); - - if (!lockedSl) { - container.SightLine.clear(); - } else { - const target = container.svg.querySelector('.sight-line-target').parentElement, - x1 = this.parentElement.dataset.x, - y1 = this.parentElement.parentElement.dataset.y, - x2 = target.dataset.x, - y2 = target.parentElement.dataset.y; - - lockedSl.setAttributeNS(null, 'x1', pos.x); - lockedSl.setAttributeNS(null, 'y1', pos.y); - - container.SightLine.drawHexes(...[x1, y1, x2, y2].map(n => parseInt(n))); - } - - this.parentElement.appendChild(counter); - container.Counter.removeClones(counter); - trace.remove(); - } else { - points = points.filter(p => p != `${pos.x},${pos.y}`).join(' '); - trace.setAttributeNS(null, 'points', points); - } - - this.remove(); - } - }, - - pointerOver = function () { - let { troopNumber, troopAllegiance } = this.dataset; - cp = container.svg.querySelector(`#clip-path-${troopAllegiance}-${troopNumber}`); - - if (cp) { - cp.style.display = 'none'; - } - }, - - pointerOut = function () { - let { troopNumber, troopAllegiance } = this.dataset; - cp = container.svg.querySelector(`#clip-path-${troopAllegiance}-${troopNumber}`); - - if (cp) { - let isVisible = - document - .getElementById('toggle-firing-arc-vis') - .querySelector(`input[data-allegiance="${troopAllegiance}"]`) - .checked; - - cp.style.display = isVisible ? 'none' : ''; - } - }, - - click = function (e) { - if (this.classList.contains(selectedClass)) { - e.stopPropagation(); - let { number: troopNumber, allegiance: troopAllegiance } = this.dataset, - trace = container.svg.querySelector(traceSelector(troopNumber, troopAllegiance)); - - if (trace) { - let points = trace.getAttribute('points').split(' '), - [clonePosX, clonePosY] = points.at(-2).split(',').map(p => parseFloat(p)), - - { clone } = Array - .from(container.getClones(troopAllegiance, troopNumber)) - .map(c => { return { clone: c, pos: container.getCellPosition(c.parentElement) }}) - .find(({ pos: { x, y }}) => x == clonePosX && y == clonePosY); - - points.pop(); - - if (points.length >= 2) { - trace.setAttributeNS(null, 'points', points.join(' ')); - } else { - trace.remove(); - } - - let sl = container.svg.querySelector('.sight-line'); - - if (sl) { - const target = container.svg.querySelector('.sight-line-target').parentElement, - { x, y } = container.getCellPosition(clone.parentElement), - x1 = clone.parentElement.dataset.x, - y1 = clone.parentElement.parentElement.dataset.y, - x2 = target.dataset.x, - y2 = target.parentElement.dataset.y; - - sl.setAttributeNS(null, 'x1', x); - sl.setAttributeNS(null, 'y1', y); - - container.SightLine.drawHexes(...[x1, y1, x2, y2].map(n => parseInt(n))); - } else { - container.SightLine.draw(this.parentElement, clone.parentElement); - } - - clone.parentElement.appendChild(this); - clone.remove(); - } - } - }, - - dblClick = function () { - if (this.classList.contains(selectedClass)) { - let { troopNumber, troopAllegiance } = this.dataset, - trace = grid.querySelector(traceSelector(troopNumber, troopAllegiance)); - - if (!trace) { - container.Counter.remove(this); - container.svg.querySelectorAll(`#firing-arcs ${dataSelector(troopNumber, troopAllegiance)}`).forEach(el => el.remove()); - } - } - }; - - this.get = function (troopNumber, allegiance) { - return container.getCounter(allegiance, troopNumber); - }; - - this.getAt = function (x, y) { - return container.querySelector(`${counterPosition(x, y)}:not(.clone)`); - }; - - this.select = function ({ dataset: { allegiance, number }}) { - this.unSelect(); - - let counter = container.getCounter(allegiance, number); - - if (counter) { - counter.classList.add(selectedClass); - } - }; - - this.unSelect = function () { - let selected = container.getSelected(); - - if (selected) { - let { troopNumber, troopAllegiance } = selected.dataset; - - selected.classList.remove(selectedClass); - selected.removeAttribute('style'); - - container - .querySelectorAll(`${selector(troopNumber, troopAllegiance)}.clone`) - .forEach(el => el.removeAttribute('style')); - } - }; - - this.isSelected = function (troopNumber, allegiance) { - return container.svg.querySelector(`${selector(troopNumber, allegiance)}.${selectedClass}`) !== null; - }; - - this.place = function ({ dataset: { troopNumber, troopAllegiance }}, point) { - let counter, points, - counterNodeList = container.getCounterAndClones(troopAllegiance, troopNumber); - - if (counterNodeList.length > 0) { - let counters = Array.from(counterNodeList), - original = counters.find(el => !el.classList.contains('clone')), - trace = container.svg.querySelector(traceSelector(troopNumber, troopAllegiance)); - - counter = original.cloneNode(); - counter.setAttributeNS(null, 'x', 0); - counter.setAttributeNS(null, 'y', 0); - counter.classList.remove(selectedClass); - counter.classList.add('clone'); - - original.setAttributeNS(null, 'x', 0); - original.setAttributeNS(null, 'y', 0); - - original.parentElement.appendChild(counter); - point.parentElement.appendChild(original); - - let previous = container.getCellPosition(counter.parentElement), - current = container.getCellPosition(original.parentElement); - - if (!trace) { - trace = document.createElementNS(svgns, 'polyline'); - - points = `${previous.x},${previous.y} ${current.x},${current.y}`; - - trace.dataset.number = troopNumber; - trace.dataset.allegiance = troopAllegiance; - trace.classList.add('move-trace'); - - container.getBoard().prepend(trace); - } else { - points = `${trace.getAttribute('points')} ${current.x},${current.y}`; - } - - trace.setAttributeNS(null, 'points', points); - counter.addEventListener('click', clickClone); - } else { - counter = document.createElementNS(svgns, 'use'), - - counter.setAttributeNS(null, 'href', `#${troopAllegiance}-${troopNumber}`); - counter.classList.add('counter', 'selected'); - counter.setAttributeNS(null, 'x', point.getAttribute('x')); - counter.setAttributeNS(null, 'y', point.getAttribute('y')); - counter.dataset.troopNumber = troopNumber; - counter.dataset.troopAllegiance = troopAllegiance; - counter.dataset.x = point.dataset.x; - counter.dataset.y = point.dataset.y; - counter.style.pointerEvents = 'auto'; - - counter.addEventListener('pointerover', pointerOver); - counter.addEventListener('pointerout', pointerOut); - counter.addEventListener('click', click); - counter.addEventListener('dblclick', dblClick); - } - - // container.querySelector(`g[data-x="${counter.dataset.x}"][data-y="${counter.dataset.y}"]`).appendChild(counter); - // container.getCell(counter.dataset.x, counter.dataset.y).appendChild(counter); - }; - - this.remove = function ({ dataset: { troopNumber, troopAllegiance }}) { - container - .querySelectorAll(dataSelector(troopNumber, troopAllegiance)) - .forEach(el => el.remove()); - }; - - this.removeClones = function ({ dataset: { allegiance, number }}) { - container.getClones(allegiance, number).forEach(el => el.remove()); - }; - - this.endMove = function (el) { - let { troopNumber, troopAllegiance } = el.dataset; - let trace = grid.querySelector(traceSelector(troopNumber, troopAllegiance)); - - if (trace) { - trace.remove(); - } - - Counter.removeClones(el); - }; - - this.hasProne = function (troopNumber, troopAllegiance) { - let selector = `g#${troopAllegiance}-${troopNumber} use[href="#counter-prone"]`; - - return !!container.svg.querySelector(selector); - }; - - this.addEventListeners = function (counter) { - // counter.addEventListener('pointerover', pointerOver); - // counter.addEventListener('pointerout', pointerOut); - counter.addEventListener('click', click); - // counter.addEventListener('dblclick', dblClick); - }; - }; - - this.getCounters().forEach(c => this.Counter.addEventListeners(c)); - } - - setUpSightLine(ptGrp) { - const svgns = "http://www.w3.org/2000/svg", - grid = this.svg.querySelector('.board'); - - this.SightLine = new function() { - this.clear = function() { - let sl = grid.querySelector('line.sight-line'); - let target = grid.querySelector(`use[href="#hex"].sight-line-target`); - - if (sl) { - sl.remove(); - } - - if (target) { - target.classList.remove('sight-line-target'); - } - - this.clearHexes(); - }; - - this.clearHexes = function() { - ptGrp.getActiveHexes().forEach(el => el.classList.remove('active')); - }; - - this.draw = function(source, target) { - ptGrp.SightLine.clear(); - - let pt = new DOMPoint(0, 0), - transform = getComputedStyle(source).transform.match(/-?\d+\.?\d*/g), - mtx = new DOMMatrix(transform); - - pt = pt.matrixTransform(mtx); - - transform = getComputedStyle(source.parentElement).transform.match(/-?\d+\.?\d*/g); - mtx = new DOMMatrix(transform); - pt = pt.matrixTransform(mtx); - - let slX1 = pt.x, - slY1 = pt.y; - - pt = new DOMPoint(0, 0); - transform = getComputedStyle(target).transform.match(/-?\d+\.?\d*/g); - mtx = new DOMMatrix(transform); - - pt = pt.matrixTransform(mtx); - - transform = getComputedStyle(target.parentElement).transform.match(/-?\d+\.?\d*/g); - mtx = new DOMMatrix(transform); - pt = pt.matrixTransform(mtx); - - let slX2 = pt.x, - slY2 = pt.y; - - let sightLine = document.createElementNS(svgns, 'line'); - - sightLine.classList.add('sight-line'); - sightLine.classList.add('active'); - sightLine.setAttributeNS(null, 'x1', slX1); - sightLine.setAttributeNS(null, 'y1', slY1); - sightLine.setAttributeNS(null, 'x2', slX2); - sightLine.setAttributeNS(null, 'y2', slY2); - - ptGrp.getBoard().appendChild(sightLine); - - let coords = [ - source.dataset.x, - source.parentElement.dataset.y, - target.dataset.x, - target.parentElement.dataset.y - ].map(n => parseInt(n)); - - this.drawHexes(...coords); - }; + }; - this.drawHexes = function(...coords) { - this.clearHexes() + this.getSelected = function () { + return document.querySelector('.soldier-record.selected'); + }; - // info.querySelector('#hex-count').textContent = offset_distance(...coords); - // info.style.display = 'block'; + this.select = function (el) { + let { troopNumber, troopAllegiance } = el.dataset; + // proneStatus = svg.Counter.hasProne(troopNumber, troopAllegiance); - let lineCoords = linedraw(...coords); + this.unSelect(); + document.querySelector(`#record-sheet .soldier-record[data-troop-number="${troopNumber}"][data-troop-allegiance="${troopAllegiance}"]`).classList.add('selected'); + // document.getElementById('toggle-prone-counter').checked = proneStatus; + }; - let s = lineCoords - .map(([x, y]) => `g[data-y="${y}"] g[data-x="${x}"] use[href="#hex"]`) - .join(', '); + this.endMove = function() { + const selected = this.getSelected(); - ptGrp.svg.querySelectorAll(s).forEach(p => p.classList.add('active')); - }; + if (selected) { + selected.classList.toggle('movement-ended'); } - } - - setFiringArc(selectedSoldier, size) { - const { troopNumber, troopAllegiance } = selectedSoldier.dataset, - counter = this.Counter.get(troopNumber, troopAllegiance), - svgns = "http://www.w3.org/2000/svg"; - - let existingArcs = this.svg.querySelectorAll( - `#firing-arcs [data-troop-number="${troopNumber}"][data-troop-allegiance="${troopAllegiance}"]` - ); - existingArcs.forEach(el => el.remove()); - - if (counter) { - let arcLayer = this.svg.querySelector('#shapes'); - let outlineLayer = this.svg.querySelector('#lines'); - let arcContainer = this.svg.querySelector('#firing-arcs'); - - let { x, y } = this.getCellPosition(counter.parentElement); - - let grid = this.svg.querySelector('.board'); - const transform = getComputedStyle(grid).transform.match(/-?\d+\.?\d*/g); - const pt = new DOMPoint(x, y); - const mtx = new DOMMatrix(transform); - let tPt = pt.matrixTransform(mtx); - - let pivotPoint = [tPt.x, tPt.y]; - let firingArc = document.createElementNS(svgns, 'polygon'); - let firingArcOutline = document.createElementNS(svgns, 'polygon'); - - firingArc.classList.add('firing-arc', 'active'); - firingArc.dataset.troopNumber = troopNumber; - firingArc.dataset.troopAllegiance = troopAllegiance; - firingArc.dataset.size = size; - firingArc.setAttributeNS(null, 'points', `${pivotPoint} ${pivotPoint} ${pivotPoint}`); - - firingArcOutline.dataset.troopNumber = troopNumber; - firingArcOutline.dataset.troopAllegiance = troopAllegiance; - firingArcOutline.setAttributeNS(null, 'points', `${pivotPoint} ${pivotPoint} ${pivotPoint}`); - - let clipShape = document.createElementNS(svgns, 'circle'); - clipShape.setAttributeNS(null, 'cx', tPt.x); - clipShape.setAttributeNS(null, 'cy', tPt.y); - clipShape.setAttributeNS(null, 'r', 100); - - let clipPath = document.createElementNS(svgns, 'clipPath'); - clipPath.setAttributeNS(null, 'id', `clip-path-${troopAllegiance}-${troopNumber}`); - clipPath.dataset.troopNumber = troopNumber; - clipPath.dataset.troopAllegiance = troopAllegiance; - clipPath.appendChild(clipShape); - - arcContainer.appendChild(clipPath); - arcLayer.appendChild(firingArc); - outlineLayer.appendChild(firingArcOutline); - - let firingArcPlacementListener = e => { - this.svg.querySelectorAll('.firing-arc.active').forEach(el => el.classList.remove('active')); - grid.removeAttribute('style'); - this.svg.removeEventListener('mousemove', this.#positionFiringArc); - firingArc.removeEventListener('click', firingArcPlacementListener); - firingArc.removeEventListener('contextmenu', cancelFiringArcPlacement); - }; - - let cancelFiringArcPlacement = e => { - e.preventDefault(); - - firingArc.removeEventListener('click', firingArcPlacementListener); - firingArc.removeEventListener('contextmenu', cancelFiringArcPlacement); - - let existingArcs = this.svg.querySelectorAll( - `#firing-arcs [data-troop-number="${troopNumber}"][data-troop-allegiance="${troopAllegiance}"]` - ); - - existingArcs.forEach(el => el.remove()); - - grid.removeAttribute('style'); - this.svg.removeEventListener('mousemove', this.#positionFiringArc); - }; - - grid.style.pointerEvents = 'none'; - this.svg.addEventListener('mousemove', this.#positionFiringArc); - firingArc.addEventListener('click', firingArcPlacementListener); - firingArc.addEventListener('contextmenu', cancelFiringArcPlacement); - } - } -} + this.unSelect(); + }; +}; window.addEventListener('load', () => { const svg = document.querySelector('object').contentDocument.querySelector('svg'), game = new Game(svg); const svgns = "http://www.w3.org/2000/svg", - ptGrp = svg.querySelector('#points'), recordSheetVisibility = document.querySelector('#content input[type="checkbox"].visible'); PanZoom.start(svg); - let info = document.getElementById('status'); + game.info = document.getElementById('status'); // Object.values(settingsPanel.querySelectorAll('fieldset')).forEach(fieldset => { // const identityMtx = [1, 0, 0, 1, 0, 0]; @@ -1068,37 +130,27 @@ window.addEventListener('load', () => { // }); // }); - const grid = svg.querySelector('#grid'); - document.querySelectorAll('.soldier-record').forEach(el => el.addEventListener('click', e => { if (el.classList.contains('selected')) { el.classList.remove('selected'); RecordSheet.unSelect(); - Counter.unSelect(); + // Counter.unSelect(); } else { RecordSheet.select(el); - Counter.select(el); + // Counter.select(el); } - SightLine.clear(); + // SightLine.clear(); }) ); - document.querySelectorAll('.end-move').forEach(el => el.addEventListener('click', e => { - let selected = RecordSheet.getSelected(); - - if (selected) { - Counter.endMove(selected); - RecordSheet.unSelect(); - selected.classList.toggle('movement-ended'); - } - })); + document.querySelectorAll('.end-move').forEach(el => el.addEventListener('click', e => game.endMove())); document.querySelectorAll('.end-turn').forEach(el => el.addEventListener('click', ({ target: { dataset: { allegiance }}}) => { let dataSelector = `[data-troop-allegiance="${allegiance}"]`, - records = Array.from(qA(`.soldier-record${dataSelector}`)), + records = Array.from(document.querySelectorAll(`.soldier-record${dataSelector}`)), turnCounter = document.getElementById('turn-count'), { textContent: count, dataset: { update }} = turnCounter; @@ -1115,24 +167,20 @@ window.addEventListener('load', () => { turnCounter.dataset.update = '1'; } - qA(`#firing-arcs ${dataSelector}`).forEach(el => el.remove()); + // qA(`#firing-arcs ${dataSelector}`).forEach(el => el.remove()); records .sort((el1, el2) => el1.dataset.troopNumber > el2.dataset.troopNumber) .forEach(el => el.classList.remove('movement-ended')); - RecordSheet.select(records.at(0)); - Counter.select(records.at(0)); + // RecordSheet.select(records.at(0)); + // Counter.select(records.at(0)); }) ); - document.querySelectorAll('.set-firing-arc').forEach(el => el.addEventListener('click', e => { - let selectedSoldier = document.querySelector('.soldier-record.selected'); - - if (selectedSoldier) { - game.setFiringArc(selectedSoldier, el.dataset.size); - } - })); + document.querySelectorAll('.set-firing-arc').forEach(el => + el.addEventListener('click', () => game.setFiringArc(el.dataset.size)) + ); recordSheetVisibility.addEventListener('input', e => { let divs = document.querySelectorAll('#content div'); @@ -1147,9 +195,7 @@ window.addEventListener('load', () => { }); document.querySelectorAll('#toggle-firing-arc-vis input').forEach(el => el.addEventListener('input', e => { - let clipPaths = svg.querySelectorAll(`clipPath[data-troop-allegiance="${el.dataset.allegiance}"]`); - - clipPaths.forEach(cp => cp.style.display = el.checked ? 'none' : ''); + game.toggleFiringArcVisibility(el.dataset.allegiance); })); document.getElementById('toggle-prone-counter').addEventListener('input', function (e) { diff --git a/src/modules/game.js b/src/modules/game.js new file mode 100644 index 0000000..2903b05 --- /dev/null +++ b/src/modules/game.js @@ -0,0 +1,906 @@ +function isEven(n) { + return n % 2 === 0; +} + +function radToDeg(radians) { + return radians * 180 / Math.PI; +} + +function calculateAngle(xDiff, yDiff) { + yDiff = -yDiff; + let angle = Math.abs(Math.atan(yDiff / xDiff)); + + if (xDiff < 0 && yDiff > 0) { + angle = Math.PI - angle; + } else if (xDiff < 0 && yDiff < 0) { + angle = Math.PI + angle; + } else if (xDiff > 0 && yDiff < 0) { + angle = 2 * Math.PI - angle; + } + + return angle; +} + +function edgePoint(x1, y1, x2, y2, maxX, maxY) { + let pointCoords, + xDiff = x2 - x1, + yDiff = y2 - y1, + xIntercept = y => (y - y1) * xDiff / yDiff + x1, + yIntercept = x => (x - x1) * yDiff / xDiff + y1; + + if (xDiff > 0 && yDiff > 0) { + let x = xIntercept(maxY); + + pointCoords = x <= maxX ? [x, maxY] : [maxX, yIntercept(maxX)]; + } else if (xDiff > 0 && yDiff < 0) { + let y = yIntercept(maxX); + + pointCoords = y >= 0 ? [maxX, y] : [xIntercept(0), 0]; + } else if (xDiff < 0 && yDiff < 0) { + let x = xIntercept(0); + + pointCoords = x >= 0 ? [x, 0] : [0, yIntercept(0)]; + } else { + let y = yIntercept(0); + + pointCoords = y <= maxY ? [0, y] : [xIntercept(maxY), maxY]; + } + + return pointCoords; +} + +function evenr_to_axial(x, y) { + return { q: x - (y + (y & 1)) / 2, r: y }; +} + +function axial_to_evenr(q, r) { + return { x: q + (r + (r & 1)) / 2, y: r }; +} + +function axial_distance(q1, r1, q2, r2) { + return (Math.abs(q1 - q2) + Math.abs(q1 + r1 - q2 - r2) + Math.abs(r1 - r2)) / 2; +} + +function offset_distance(x1, y1, x2, y2) { + let { q: q1, r: r1 } = evenr_to_axial(x1, y1), + { q: q2, r: r2 } = evenr_to_axial(x2, y2); + + return axial_distance(q1, r1, q2, r2); +} + +function cube_to_axial(q, r, s) { + return { q: q, r: r }; +} + +function axial_to_cube(q, r) { + return { q: q, r: r, s: -q - r }; +} + +function cube_round(q, r, s) { + rQ = Math.round(q); + rR = Math.round(r); + rS = Math.round(s); + + let q_diff = Math.abs(rQ - q), + r_diff = Math.abs(rR - r), + s_diff = Math.abs(rS - s); + + if (q_diff > r_diff && q_diff > s_diff) { + rQ = -rR - rS; + } else if (r_diff > s_diff) { + rR = -rQ - rS; + } else { + rS = -rQ - rR; + } + + return { q: rQ, r: rR, s: rS }; +} + +function axial_round(q, r) { + let cube = axial_to_cube(q, r), + round = cube_round(cube.q, cube.r, cube.s), + axial = cube_to_axial(round.q, round.r, round.s); + + return { q: axial.q, r: axial.r }; +} + +function lerp(a, b, t) { + return a + (b - a) * t; +} + +function axial_lerp(q1, r1, q2, r2, t) { + return { q: lerp(q1, q2, t), r: lerp(r1, r2, t) }; +} + +function linedraw(x1, y1, x2, y2) { + let axial1 = evenr_to_axial(x1, y1), + axial2 = evenr_to_axial(x2, y2), + n = offset_distance(x1, y1, x2, y2), + results = []; + + for (let i = 0; i <= n; i++) { + let lerp = axial_lerp(axial1.q, axial1.r, axial2.q, axial2.r, 1.0 / n * i), + round = axial_round(lerp.q, lerp.r), + { x, y } = axial_to_evenr(round.q, round.r); + + results.push([x, y]); + } + + return results; +} + +export default class Game { + info; + + #firingArcVisibility = { + davion: false, + liao: false + }; + + constructor(svg) { + this.svg = svg; + + this.setUpSightLine(this); + this.setUpCounter(this); + // this.setUpRecordSheet(); + this.setUpCells(); + } + + static HORZ_POINT_DISTANCE = 1.005; + static VERT_POINT_DISTANCE = Math.sqrt(3) * Game.HORZ_POINT_DISTANCE / 2; + + static FIRING_ARC_SIZE = { + 'small': Math.atan(Game.HORZ_POINT_DISTANCE / (6 * Game.VERT_POINT_DISTANCE)), + 'medium': Math.atan((Game.HORZ_POINT_DISTANCE / 2) / Game.VERT_POINT_DISTANCE), + 'large': Math.atan((21 * Game.HORZ_POINT_DISTANCE) / (6 * Game.VERT_POINT_DISTANCE)) + }; + + #positionFiringArc(e) { + let activeFiringArc = this.querySelector('polygon.firing-arc.active'); + + // TODO: handle exactly horizontal and vertical lines + + if (activeFiringArc) { + let activeFiringArcOutline = this.querySelector(`#lines polygon[data-troop-number="${activeFiringArc.dataset.troopNumber}"][data-troop-allegiance="${activeFiringArc.dataset.troopAllegiance}"]`), + board = this.querySelector('#image-maps'), + { width, height } = board.getBBox(), + pt = new DOMPoint(e.clientX, e.clientY), + { x: pointerX, y: pointerY } = pt.matrixTransform(board.getScreenCTM().inverse()), + [maxXpx, maxYpx] = [width, height], + { x: x1px, y: y1px } = activeFiringArc.points[0]; + + let [x2px, y2px] = [ + pointerX / width * maxXpx, + pointerY / height * maxYpx + ]; + + let xDiff = x2px - x1px; + let yDiff = y2px - y1px; + let angle = calculateAngle(xDiff, yDiff); + + let arcAngle = Game.FIRING_ARC_SIZE[activeFiringArc.dataset.size]; + let distance = Math.sqrt((x2px - x1px) ** 2 + (y2px - y1px) ** 2); + let yDelta = distance * Math.cos(angle) * Math.tan(arcAngle); + let xDelta = distance * Math.sin(angle) * Math.tan(arcAngle); + + let [newY1, newX1] = [y2px + yDelta, x2px + xDelta]; + let [newY2, newX2] = [y2px - yDelta, x2px - xDelta]; + + [newX1, newY1] = edgePoint(x1px, y1px, newX1, newY1, maxXpx, maxYpx); + [newX2, newY2] = edgePoint(x1px, y1px, newX2, newY2, maxXpx, maxYpx); + + let oppositeEdgeConditions = [ + newX1 == 0 && newX2 == maxXpx, + newX2 == 0 && newX1 == maxXpx, + newY1 == 0 && newY2 == maxYpx, + newY2 == 0 && newY1 == maxYpx + ] + + let orthogonalEdgeConditions = [ + (newX1 == 0 || newX1 == maxXpx) && (newY2 == 0 || newY2 == maxYpx), + (newX2 == 0 || newX2 == maxXpx) && (newY1 == 0 || newY1 == maxYpx), + ] + + let points; + + if (oppositeEdgeConditions.some(e => e)) { + let cornerPoints; + + if (xDiff > 0 && yDiff > 0) { + if ((newY1 == 0 && newY2 == maxYpx) || (newY1 == maxYpx && newY2 == 0)) { + cornerPoints = [[maxXpx, 0], [maxXpx, maxYpx]]; + } else { + cornerPoints = [[maxXpx, maxYpx], [0, maxYpx]]; + } + } else if (xDiff > 0 && yDiff < 0) { + if ((newY1 == 0 && newY2 == maxYpx) || (newY1 == maxYpx && newY2 == 0)) { + cornerPoints = [[maxXpx, 0], [maxXpx, maxYpx]]; + } else { + cornerPoints = [[0, 0], [maxXpx, 0]]; + } + + } else if (xDiff < 0 && yDiff > 0) { + if ((newY1 == 0 && newY2 == maxYpx) || (newY1 == maxYpx && newY2 == 0)) { + cornerPoints = [[0, maxYpx], [0, 0]]; + } else { + cornerPoints = [[maxXpx, maxYpx], [0, maxYpx]]; + } + + } else { + if ((newY1 == 0 && newY2 == maxYpx) || (newY1 == maxYpx && newY2 == 0)) { + cornerPoints = [[0, maxYpx], [0, 0]]; + } else { + cornerPoints = [[0, 0], [maxXpx, 0]]; + } + + } + points = `${x1px},${y1px} ${newX1},${newY1} ${cornerPoints[1]} ${cornerPoints[0]} ${newX2},${newY2}`; + } else if (orthogonalEdgeConditions.some(e => e)) { + let cornerPoints = []; + let cp1, cp2; + + if (newX1 == 0 || newX1 == maxXpx) { + cp1 = [newX1, yDiff > 0 ? maxYpx : 0]; + } else { + cp1 = [xDiff > 0 ? maxXpx : 0, newY1]; + } + + if (newX2 == 0 || newX2 == maxXpx) { + cp2 = [newX2, yDiff > 0 ? maxYpx : 0]; + } else { + cp2 = [xDiff > 0 ? maxXpx : 0, newY2]; + } + + if (cp1[0] == cp2[0] && cp1[1] == cp2[1]) { + cornerPoints.push(cp1); + } else { + cornerPoints.push(cp1); + cornerPoints.push([xDiff > 0 ? maxXpx : 0, yDiff > 0 ? maxYpx : 0]) + cornerPoints.push(cp2); + } + + points = `${x1px},${y1px} ${newX1},${newY1} ${cornerPoints.join(' ')} ${newX2},${newY2}`; + } else { + points = `${x1px},${y1px} ${newX1},${newY1} ${newX2},${newY2}`; + } + + activeFiringArcOutline.setAttributeNS(null, 'points', points); + activeFiringArc.setAttributeNS(null, 'points', points); + } + } + + getCells() { + return this.svg.querySelectorAll('g[data-x]'); + } + + getCell(x, y) { + return this.svg.querySelector(`g[data-y="${y}"] g[data-x="${x}"]`); + } + + getHex(cell) { + return cell.querySelector('use[href="#hex"]'); + } + + getCounters() { + return this.svg.querySelectorAll(`use[data-allegiance][data-number]:not(.clone)`); + } + + getCounter(al, n) { + return this.svg.querySelector(`use[data-allegiance="${al}"][data-number="${n}"]:not(.clone)`); + } + + getCounterAndClones(al, n) { + return this.svg.querySelectorAll(`use[data-allegiance="${al}"][data-number="${n}"]`); + } + + getClones(al, n) { + return this.svg.querySelectorAll(`use[data-allegiance="${al}"][data-number="${n}"].clone`); + } + + getSelected() { + return this.svg.querySelector(`use[data-allegiance][data-number].selected`); + } + + getSightLine() { + return this.svg.querySelector('line.sight-line'); + } + + getExistingArcs(al, n) { + return this.svg.querySelectorAll(`#firing-arcs polygon[data-troop-number="${n}"][data-troop-allegiance="${al}"]`); + } + + getUnclippedFiringArcs() { + return this.svg.querySelectorAll('#firing-arcs polygon:not([clip-path])'); + } + + getGridIndex({ parentElement }) { + return { x: parentElement.dataset.x, y: parentElement.parentElement.dataset.y }; + } + + getBoard() { + return this.svg.querySelector('.board'); + } + + getActiveHexes() { + return this.svg.querySelectorAll('use[href="#hex"].active'); + } + + getCellPosition(cell) { + let pt = new DOMPoint(0, 0), + transform = getComputedStyle(cell).transform.match(/-?\d+\.?\d*/g), + mtx = new DOMMatrix(transform); + pt = pt.matrixTransform(mtx); + + transform = getComputedStyle(cell.parentElement).transform.match(/-?\d+\.?\d*/g); + mtx = new DOMMatrix(transform); + pt = pt.matrixTransform(mtx); + + return pt; + } + + endMove() { + const selected = this.getSelected(); + + if (selected) { + this.Counter.endMove(selected); + // this.RecordSheet.endMove(); + } + } + + toggleFiringArcVisibility(allegiance) { + const vis = this.#firingArcVisibility[allegiance], + clipPaths = this.svg.querySelectorAll(`clipPath[data-troop-allegiance="${allegiance}"]`); + + clipPaths.forEach(cp => cp.style.display = !vis ? 'none' : ''); + this.#firingArcVisibility[allegiance] = !vis; + } + + clipFiringArcs() { + let unclipped = this.getUnclippedFiringArcs(); + + unclipped.forEach(el => { + const { troopNumber, troopAllegiance } = el.dataset, + clipPathId = `clip-path-${troopAllegiance}-${troopNumber}`, + isVisible = this.#firingArcVisibility[troopAllegiance]; + + if (isVisible) { + this.svg.querySelector(`#${clipPathId}`).style.display = 'none'; + } + + el.setAttributeNS(null, 'clip-path', `url(#${clipPathId})`); + }); + } + + setUpCells() { + this.getCells().forEach(cell => { + let group = cell, + point = this.getHex(cell); + + point.addEventListener('click', e => { + // TODO + let existingOccupant = + this.svg.querySelector(`.counter[data-x="${point.dataset.x}"][data-y="${point.dataset.y}"]`); + + if (this.getSelected() && !existingOccupant) { + let sl = this.svg.querySelector('.sight-line'); + + this.Counter.place(point); + + if (sl) { + if (sl.classList.contains('active')) { + this.SightLine.clear(); + } else { + this.SightLine.update(point); + } + } + } + }); + + group.addEventListener('contextmenu', e => { + e.preventDefault(); + let sl = this.svg.querySelector('.sight-line'); + + if (sl) { + sl.classList.toggle('active'); + + if (sl.classList.contains('active')) { + this.SightLine.clear(); + } else { + group.querySelector(`use[href="#hex"]`).classList.add('sight-line-target'); + } + + group.dispatchEvent(new MouseEvent('pointerover')); + } + }); + + group.addEventListener('pointerover', e => { + let selected = this.getSelected(); + + if (selected) { + let sl = this.svg.querySelector('.sight-line'), + isOnBoard = selected.parentElement.hasAttribute('data-x'), + sourceCell = selected.parentElement; + + if (isOnBoard && (!sl || sl.classList.contains('active')) && sourceCell != group) { + this.SightLine.draw(sourceCell, group); + } + } + }); + + group.addEventListener('pointerout', e => { + let sl = this.svg.querySelector('.sight-line.active'); + + if (sl && sl.classList.contains('active')) { + this.SightLine.clear(); + } + }); + }); + } + + setUpCounter(container) { + this.Counter = new function () { + let selectedClass = 'selected', + svgns = "http://www.w3.org/2000/svg", + + dataSelector = function (troopNumber, allegiance) { + return `[data-number="${troopNumber}"][data-allegiance="${allegiance}"]`; + }, + + selector = function (troopNumber, allegiance) { + return `use.counter${dataSelector(troopNumber, allegiance)}`; + }, + + position = function (x, y) { + return `g[data-x="${x}"][data-y="${y}"]`; + }, + + counterPosition = function (x, y) { + return `use.counter[data-x="${x}"][data-x="${y}"]`; + }, + + traceSelector = function (troopNumber, allegiance) { + return `polyline.move-trace${dataSelector(troopNumber, allegiance)}`; + }, + + clickClone = function (e) { + e.stopPropagation(); + + let { number: troopNumber, allegiance: troopAllegiance } = this.dataset, + pos = container.getCellPosition(this.parentElement); + + if (container.Counter.isSelected(troopNumber, troopAllegiance)) { + let trace = container.svg.querySelector(traceSelector(troopNumber, troopAllegiance)), + points = trace.getAttribute('points').split(' '); + + if (`${pos.x},${pos.y}` == points.at(0)) { + const counter = container.getCounter(troopAllegiance, troopNumber), + lockedSl = container.svg.querySelector('.sight-line:not(.active)'); + + counter.setAttributeNS(null, 'x', 0); + counter.setAttributeNS(null, 'y', 0); + + if (!lockedSl) { + container.SightLine.clear(); + } else { + container.SightLine.update(this); + } + + this.parentElement.appendChild(counter); + container.Counter.removeClones(counter); + trace.remove(); + } else { + points = points.filter(p => p != `${pos.x},${pos.y}`).join(' '); + trace.setAttributeNS(null, 'points', points); + } + + this.remove(); + } + }, + + pointerOver = function () { + let { number: troopNumber, allegiance: troopAllegiance } = this.dataset, + cp = container.svg.querySelector(`#clip-path-${troopAllegiance}-${troopNumber}`); + + if (cp) { + cp.style.display = 'none'; + } + }, + + pointerOut = function () { + let { number: troopNumber, allegiance: troopAllegiance } = this.dataset, + cp = container.svg.querySelector(`#clip-path-${troopAllegiance}-${troopNumber}`); + + if (cp) { + let isVisible = + document + .getElementById('toggle-firing-arc-vis') + .querySelector(`input[data-allegiance="${troopAllegiance}"]`) + .checked; + + cp.style.display = isVisible ? 'none' : ''; + } + }, + + click = function (e) { + if (this.classList.contains(selectedClass)) { + e.stopPropagation(); + let { number: troopNumber, allegiance: troopAllegiance } = this.dataset, + trace = container.svg.querySelector(traceSelector(troopNumber, troopAllegiance)); + + if (trace) { + let points = trace.getAttribute('points').split(' '), + [clonePosX, clonePosY] = points.at(-2).split(',').map(p => parseFloat(p)), + + { clone } = Array + .from(container.getClones(troopAllegiance, troopNumber)) + .map(c => { return { clone: c, pos: container.getCellPosition(c.parentElement) }}) + .find(({ pos: { x, y }}) => x == clonePosX && y == clonePosY); + + points.pop(); + + if (points.length >= 2) { + trace.setAttributeNS(null, 'points', points.join(' ')); + } else { + trace.remove(); + } + + let sl = container.svg.querySelector('.sight-line'); + + if (sl) { + container.SightLine.update(clone) + } else { + container.SightLine.draw(this.parentElement, clone.parentElement); + } + + clone.parentElement.appendChild(this); + clone.remove(); + } + } else { + e.stopPropagation(); + // this.RecordSheet.select(e.target); + container.Counter.select(e.target); + } + }, + + dblClick = function () { + if (this.classList.contains(selectedClass)) { + let { troopNumber, troopAllegiance } = this.dataset, + trace = grid.querySelector(traceSelector(troopNumber, troopAllegiance)); + + if (!trace) { + container.Counter.remove(this); + container.svg.querySelectorAll(`#firing-arcs ${dataSelector(troopNumber, troopAllegiance)}`).forEach(el => el.remove()); + } + } + }; + + this.get = function (troopNumber, allegiance) { + return container.getCounter(allegiance, troopNumber); + }; + + this.getAt = function (x, y) { + return container.querySelector(`${counterPosition(x, y)}:not(.clone)`); + }; + + this.select = function ({ dataset: { allegiance, number }}) { + this.unSelect(); + + let counter = container.getCounter(allegiance, number); + + if (counter) { + counter.classList.add(selectedClass); + let existingArcs = container.getExistingArcs(allegiance, number); + existingArcs.forEach(el => el.removeAttribute('clip-path')); + } + }; + + this.unSelect = function () { + let selected = container.getSelected(); + + if (selected) { + let { troopNumber, troopAllegiance } = selected.dataset; + + selected.classList.remove(selectedClass); + selected.removeAttribute('style'); + container.SightLine.clear(); + + container + .svg + .querySelectorAll(`${selector(troopNumber, troopAllegiance)}.clone`) + .forEach(el => el.removeAttribute('style')); + } + + container.clipFiringArcs(); + }; + + this.isSelected = function (troopNumber, allegiance) { + return container.svg.querySelector(`${selector(troopNumber, allegiance)}.${selectedClass}`) !== null; + }; + + this.place = function (point) { + const selected = container.getSelected(), + troopAllegiance = selected.dataset.allegiance, + troopNumber = selected.dataset.number; + + let counter, points, + counterNodeList = container.getCounterAndClones(troopAllegiance, troopNumber); + + if (counterNodeList.length > 0 && selected.parentElement.hasAttribute('data-x')) { + let counters = Array.from(counterNodeList), + original = counters.find(el => !el.classList.contains('clone')), + trace = container.svg.querySelector(traceSelector(troopNumber, troopAllegiance)); + + counter = original.cloneNode(); + counter.setAttributeNS(null, 'x', 0); + counter.setAttributeNS(null, 'y', 0); + counter.classList.remove(selectedClass); + counter.classList.add('clone'); + + original.setAttributeNS(null, 'x', 0); + original.setAttributeNS(null, 'y', 0); + + original.parentElement.appendChild(counter); + point.parentElement.appendChild(original); + + let previous = container.getCellPosition(counter.parentElement), + current = container.getCellPosition(original.parentElement); + + if (!trace) { + trace = document.createElementNS(svgns, 'polyline'); + + points = `${previous.x},${previous.y} ${current.x},${current.y}`; + + trace.dataset.number = troopNumber; + trace.dataset.allegiance = troopAllegiance; + trace.classList.add('move-trace'); + + container.getBoard().prepend(trace); + } else { + points = `${trace.getAttribute('points')} ${current.x},${current.y}`; + } + + trace.setAttributeNS(null, 'points', points); + counter.addEventListener('click', clickClone); + } else { + selected.removeAttribute('data-x'); + point.parentElement.appendChild(selected); + } + }; + + this.remove = function ({ dataset: { troopNumber, troopAllegiance }}) { + container + .querySelectorAll(dataSelector(troopNumber, troopAllegiance)) + .forEach(el => el.remove()); + }; + + this.removeClones = function ({ dataset: { allegiance, number }}) { + container.getClones(allegiance, number).forEach(el => el.remove()); + }; + + this.endMove = function (el) { + let { number: troopNumber, allegiance: troopAllegiance } = el.dataset; + let trace = container.svg.querySelector(traceSelector(troopNumber, troopAllegiance)); + + if (trace) { + trace.remove(); + } + + this.removeClones(el); + this.unSelect(); + }; + + this.hasProne = function (troopNumber, troopAllegiance) { + let selector = `g#${troopAllegiance}-${troopNumber} use[href="#counter-prone"]`; + + return !!container.svg.querySelector(selector); + }; + + this.addEventListeners = function (counter) { + counter.addEventListener('pointerover', pointerOver); + counter.addEventListener('pointerout', pointerOut); + counter.addEventListener('click', click); + // counter.addEventListener('dblclick', dblClick); + }; + }; + + this.getCounters().forEach(c => this.Counter.addEventListeners(c)); + } + + setUpSightLine(ptGrp) { + const svgns = "http://www.w3.org/2000/svg", + grid = this.svg.querySelector('.board'); + + this.SightLine = new function() { + this.clear = function() { + let sl = grid.querySelector('line.sight-line'); + let target = grid.querySelector(`use[href="#hex"].sight-line-target`); + + if (sl) { + sl.remove(); + } + + if (target) { + target.classList.remove('sight-line-target'); + } + + this.clearHexes(); + }; + + this.clearHexes = function() { + if (ptGrp.info) { + ptGrp.info.querySelector('#hex-count').textContent = '-'; + ptGrp.info.style.display = 'none'; + } + + ptGrp.getActiveHexes().forEach(el => el.classList.remove('active')); + }; + + this.draw = function (source, target) { + ptGrp.SightLine.clear(); + + let pt = new DOMPoint(0, 0), + transform = getComputedStyle(source).transform.match(/-?\d+\.?\d*/g), + mtx = new DOMMatrix(transform); + + pt = pt.matrixTransform(mtx); + + transform = getComputedStyle(source.parentElement).transform.match(/-?\d+\.?\d*/g); + mtx = new DOMMatrix(transform); + pt = pt.matrixTransform(mtx); + + let slX1 = pt.x, + slY1 = pt.y; + + pt = new DOMPoint(0, 0); + transform = getComputedStyle(target).transform.match(/-?\d+\.?\d*/g); + mtx = new DOMMatrix(transform); + + pt = pt.matrixTransform(mtx); + + transform = getComputedStyle(target.parentElement).transform.match(/-?\d+\.?\d*/g); + mtx = new DOMMatrix(transform); + pt = pt.matrixTransform(mtx); + + let slX2 = pt.x, + slY2 = pt.y; + + let sightLine = document.createElementNS(svgns, 'line'); + + sightLine.classList.add('sight-line'); + sightLine.classList.add('active'); + sightLine.setAttributeNS(null, 'x1', slX1); + sightLine.setAttributeNS(null, 'y1', slY1); + sightLine.setAttributeNS(null, 'x2', slX2); + sightLine.setAttributeNS(null, 'y2', slY2); + + ptGrp.getBoard().appendChild(sightLine); + + let coords = [ + source.dataset.x, + source.parentElement.dataset.y, + target.dataset.x, + target.parentElement.dataset.y + ].map(n => parseInt(n)); + + this.drawHexes(...coords); + }; + + this.update = function (cell) { + const sl = ptGrp.svg.querySelector('.sight-line'), + target = ptGrp.svg.querySelector('.sight-line-target').parentElement, + { x, y } = ptGrp.getCellPosition(cell.parentElement), + x1 = cell.parentElement.dataset.x, + y1 = cell.parentElement.parentElement.dataset.y, + x2 = target.dataset.x, + y2 = target.parentElement.dataset.y; + + sl.setAttributeNS(null, 'x1', x); + sl.setAttributeNS(null, 'y1', y); + + this.drawHexes(...[x1, y1, x2, y2].map(n => parseInt(n))); + } + + this.drawHexes = function (...coords) { + this.clearHexes() + + if (ptGrp.info) { + ptGrp.info.querySelector('#hex-count').textContent = offset_distance(...coords); + ptGrp.info.style.display = 'block'; + } + + let lineCoords = linedraw(...coords); + + let s = lineCoords + .map(([x, y]) => `g[data-y="${y}"] g[data-x="${x}"] use[href="#hex"]`) + .join(', '); + + ptGrp.svg.querySelectorAll(s).forEach(p => p.classList.add('active')); + }; + } + } + + setFiringArc(size) { + const svgns = "http://www.w3.org/2000/svg", + counter = this.getSelected(); + + if (counter) { + const { allegiance: troopAllegiance, number: troopNumber } = counter.dataset; + + let existingArcs = this.svg.querySelectorAll( + `#firing-arcs [data-troop-number="${troopNumber}"][data-troop-allegiance="${troopAllegiance}"]` + ); + + existingArcs.forEach(el => el.remove()); + + let arcLayer = this.svg.querySelector('#shapes'); + let outlineLayer = this.svg.querySelector('#lines'); + let arcContainer = this.svg.querySelector('#firing-arcs'); + + let { x, y } = this.getCellPosition(counter.parentElement); + + let grid = this.svg.querySelector('.board'); + const transform = getComputedStyle(grid).transform.match(/-?\d+\.?\d*/g); + const pt = new DOMPoint(x, y); + const mtx = new DOMMatrix(transform); + let tPt = pt.matrixTransform(mtx); + + let pivotPoint = [tPt.x, tPt.y]; + let firingArc = document.createElementNS(svgns, 'polygon'); + let firingArcOutline = document.createElementNS(svgns, 'polygon'); + + firingArc.classList.add('firing-arc', 'active'); + firingArc.dataset.troopNumber = troopNumber; + firingArc.dataset.troopAllegiance = troopAllegiance; + firingArc.dataset.size = size; + firingArc.setAttributeNS(null, 'points', `${pivotPoint} ${pivotPoint} ${pivotPoint}`); + + firingArcOutline.dataset.troopNumber = troopNumber; + firingArcOutline.dataset.troopAllegiance = troopAllegiance; + firingArcOutline.setAttributeNS(null, 'points', `${pivotPoint} ${pivotPoint} ${pivotPoint}`); + + let clipShape = document.createElementNS(svgns, 'circle'); + clipShape.setAttributeNS(null, 'cx', tPt.x); + clipShape.setAttributeNS(null, 'cy', tPt.y); + clipShape.setAttributeNS(null, 'r', 100); + + let clipPath = document.createElementNS(svgns, 'clipPath'); + clipPath.setAttributeNS(null, 'id', `clip-path-${troopAllegiance}-${troopNumber}`); + clipPath.dataset.troopNumber = troopNumber; + clipPath.dataset.troopAllegiance = troopAllegiance; + clipPath.appendChild(clipShape); + + arcContainer.appendChild(clipPath); + arcLayer.appendChild(firingArc); + outlineLayer.appendChild(firingArcOutline); + + let firingArcPlacementListener = e => { + this.svg.querySelectorAll('.firing-arc.active').forEach(el => el.classList.remove('active')); + grid.removeAttribute('style'); + this.svg.removeEventListener('mousemove', this.#positionFiringArc); + firingArc.removeEventListener('click', firingArcPlacementListener); + firingArc.removeEventListener('contextmenu', cancelFiringArcPlacement); + }; + + let cancelFiringArcPlacement = e => { + e.preventDefault(); + + firingArc.removeEventListener('click', firingArcPlacementListener); + firingArc.removeEventListener('contextmenu', cancelFiringArcPlacement); + + let existingArcs = this.svg.querySelectorAll( + `#firing-arcs [data-troop-number="${troopNumber}"][data-troop-allegiance="${troopAllegiance}"]` + ); + + existingArcs.forEach(el => el.remove()); + + grid.removeAttribute('style'); + this.svg.removeEventListener('mousemove', this.#positionFiringArc); + }; + + grid.style.pointerEvents = 'none'; + this.svg.addEventListener('mousemove', this.#positionFiringArc); + firingArc.addEventListener('click', firingArcPlacementListener); + firingArc.addEventListener('contextmenu', cancelFiringArcPlacement); + } + } +} -- cgit v1.2.3