index : btroops | |
Virtual board game-aid for BattleTroops, an infantry combat simulator wargame published by FASA in 1989. |
aboutsummaryrefslogtreecommitdiff |
diff options
Diffstat (limited to 'src/modules/game')
-rw-r--r-- | src/modules/game/counter.js | 148 | ||||
-rw-r--r-- | src/modules/game/firingArc.js | 304 | ||||
-rw-r--r-- | src/modules/game/sightLine.js | 199 |
3 files changed, 651 insertions, 0 deletions
diff --git a/src/modules/game/counter.js b/src/modules/game/counter.js new file mode 100644 index 0000000..69552d8 --- /dev/null +++ b/src/modules/game/counter.js @@ -0,0 +1,148 @@ +const svgns = "http://www.w3.org/2000/svg"; + +export default class Counter { + constructor(svg) { + this.svg = svg; + this.selectedClass = 'selected'; + } + + dataSelector({ dataset: { allegiance, number }}) { + return `[data-number="${number}"][data-allegiance="${allegiance}"]`; + } + + position(x, y) { + return `g[data-x="${x}"][data-y="${y}"]`; + } + + counterPosition(x, y) { + return `.counter[data-x="${x}"][data-x="${y}"]`; + } + + traceSelector(counter) { + return `polyline.move-trace${this.dataSelector(counter)}`; + } + + getClones(counter) { + return this.svg.querySelectorAll(`.counter.clone${this.dataSelector(counter)}`); + } + + getCounter(selected) { + return this.svg.querySelector(`.counter${this.dataSelector(selected)}:not(.clone)`); + } + + getCounterAndClones(counter) { + return this.svg.querySelectorAll(`.counter${this.dataSelector(counter)}`); + } + + getTrace(counter) { + return this.svg.querySelector(this.traceSelector(counter)); + } + + 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; + } + + getBoard() { + return this.svg.querySelector('.board'); + } + + place(selected, cell) { + let points, + counterNodeList = this.getCounterAndClones(selected); + + if (counterNodeList.length > 0 && selected.parentElement.hasAttribute('data-x')) { + let trace = this.svg.querySelector(this.traceSelector(selected)); + + let prevCoords = [ + selected.parentElement.dataset.x, + selected.parentElement.parentElement.dataset.y + ] + + let clone = selected.cloneNode(true); + clone.classList.remove(this.selectedClass); + clone.classList.add('clone'); + + selected.dataset.previous = prevCoords; + selected.parentElement.appendChild(clone); + cell.appendChild(selected); + + selected.childNodes.forEach(n => { + if (n.classList.contains('removed')) { + n.remove(); + } else if ('preexisting' in n.dataset) { + delete n.dataset.preexisting; + } + }); + + let previous = this.getCellPosition(clone.parentElement), + current = this.getCellPosition(selected.parentElement); + + if (!trace) { + trace = document.createElementNS(svgns, 'polyline'); + + points = `${previous.x},${previous.y} ${current.x},${current.y}`; + + trace.dataset.number = selected.dataset.number; + trace.dataset.allegiance = selected.dataset.allegiance; + trace.classList.add('move-trace'); + + this.getBoard().prepend(trace); + } else { + points = `${trace.getAttribute('points')} ${current.x},${current.y}`; + } + + trace.setAttributeNS(null, 'points', points); + } else { + selected.removeAttribute('data-x'); + cell.appendChild(selected); + } + } + + removeClones(counter) { + this.getClones(counter).forEach(c => c.remove()); + } + + endMove(counter) { + const trace = this.svg.querySelector(this.traceSelector(counter)), + proneCounter = counter.querySelector('[href="#counter-prone"]'); + + if (trace) { + trace.remove(); + } + + delete counter.dataset.previous; + + if (proneCounter) { + proneCounter.dataset.preexisting = ''; + } + + this.removeClones(counter); + } + + hasProne(counter) { + return !!counter.querySelector('[href="#counter-prone"]'); + } + + toggleProne(counter) { + let proneCounter = counter.querySelector('[href="#counter-prone"]'); + + if (!proneCounter) { + proneCounter = document.createElementNS(svgns, 'use'); + proneCounter.setAttributeNS(null, 'href', '#counter-prone'); + counter.appendChild(proneCounter); + } else if ('preexisting' in proneCounter.dataset) { + proneCounter.classList.toggle('removed'); + } else { + proneCounter.remove(); + } + } +} diff --git a/src/modules/game/firingArc.js b/src/modules/game/firingArc.js new file mode 100644 index 0000000..d2f18a5 --- /dev/null +++ b/src/modules/game/firingArc.js @@ -0,0 +1,304 @@ +// https://www.redblobgames.com/grids/hexagons/ + +// Horizontal distance between hex centers is sqrt(3) * size. The vertical +// distance is 3 / 2 * size. When we calculate horzDist / vertDist, the size +// cancels out, leaving us with a unitless ratio of sqrt(3) / (3 / 2), or +// 2 * sqrt(3) / 3. + +const svgns = "http://www.w3.org/2000/svg", + horzToVertDistRatio = 2 * Math.sqrt(3) / 3, + + arcSize = { + 'small': Math.atan(horzToVertDistRatio / 6), + 'medium': Math.atan(horzToVertDistRatio / 2), + 'large': Math.atan(7 * horzToVertDistRatio / 2) + }, + + firingArcVisibility = { + davion: false, + liao: false + }; + +let svg; + +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 position(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-number="${activeFiringArc.dataset.number}"][data-allegiance="${activeFiringArc.dataset.allegiance}"]`), + 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 = arcSize[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); + } +} + +function setDataAttrs({ dataset: { allegiance, number }}, el) { + el.dataset.allegiance = allegiance; + el.dataset.number = number; +} + +function getClipPathId({ dataset: { allegiance, number }}) { + return `clip-path-${allegiance}-${number}`; +} + +function getUnclipped() { + return svg.querySelectorAll('#firing-arcs polygon:not([clip-path])'); +}; + +export default function (el) { + svg = el; + + this.set = function (size, counter, { x, y }) { + this.get(counter).forEach(fa => fa.remove()); + + let arcLayer = svg.querySelector('#shapes'); + let outlineLayer = svg.querySelector('#lines'); + let arcContainer = svg.querySelector('#firing-arcs'); + + let grid = 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'); + + setDataAttrs(counter, firingArc); + firingArc.dataset.size = size; + firingArc.classList.add('firing-arc', 'active'); + firingArc.setAttributeNS(null, 'points', `${pivotPoint} ${pivotPoint} ${pivotPoint}`); + + setDataAttrs(counter, firingArcOutline); + 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'); + setDataAttrs(counter, clipPath); + clipPath.setAttributeNS(null, 'id', getClipPathId(counter)); + clipPath.appendChild(clipShape); + + arcContainer.appendChild(clipPath); + arcLayer.appendChild(firingArc); + outlineLayer.appendChild(firingArcOutline); + + let firingArcPlacementListener = e => { + svg.querySelectorAll('.firing-arc.active').forEach(el => el.classList.remove('active')); + grid.removeAttribute('style'); + svg.removeEventListener('mousemove', position); + firingArc.removeEventListener('click', firingArcPlacementListener); + firingArc.removeEventListener('contextmenu', cancelFiringArcPlacement); + }; + + let cancelFiringArcPlacement = e => { + e.preventDefault(); + + firingArc.removeEventListener('click', firingArcPlacementListener); + firingArc.removeEventListener('contextmenu', cancelFiringArcPlacement); + + this.get(counter).forEach(fa => fa.remove()); + + grid.removeAttribute('style'); + svg.removeEventListener('mousemove', position); + }; + + grid.style.pointerEvents = 'none'; + svg.addEventListener('mousemove', position); + firingArc.addEventListener('click', firingArcPlacementListener); + firingArc.addEventListener('contextmenu', cancelFiringArcPlacement); + }; + + this.clear = function (allegiance) { + const selector = `#firing-arcs [data-allegiance="${allegiance}"]`; + svg.querySelectorAll(selector).forEach(el => el.remove()); + }; + + this.get = function ({ dataset: { allegiance, number }}) { + return svg.querySelectorAll(`#firing-arcs polygon[data-number="${number}"][data-allegiance="${allegiance}"]`); + }; + + this.toggleVisibility = function (allegiance) { + const vis = firingArcVisibility[allegiance], + clipPaths = svg.querySelectorAll(`clipPath[data-allegiance="${allegiance}"]`); + + clipPaths.forEach(cp => cp.style.display = !vis ? 'none' : ''); + firingArcVisibility[allegiance] = !vis; + }; + + this.toggleCounterVisibility = function ({ dataset: { number, allegiance }}, vis) { + const cp = svg.querySelector(`#clip-path-${allegiance}-${number}`), + display = vis ? 'none' : ''; + + if (cp) { + cp.style.display = firingArcVisibility[allegiance] ? 'none' : display; + } + }; + + this.clipAll = function () { + console.log('clipall') + let unclipped = getUnclipped(); + + unclipped.forEach(el => { + const { number, allegiance } = el.dataset, + clipPathId = `clip-path-${allegiance}-${number}`, + isVisible = firingArcVisibility[allegiance]; + + if (isVisible) { + svg.querySelector(`#${clipPathId}`).style.display = 'none'; + } + + el.setAttributeNS(null, 'clip-path', `url(#${clipPathId})`); + }); + }; +} diff --git a/src/modules/game/sightLine.js b/src/modules/game/sightLine.js new file mode 100644 index 0000000..4790bd8 --- /dev/null +++ b/src/modules/game/sightLine.js @@ -0,0 +1,199 @@ +const svgns = "http://www.w3.org/2000/svg"; + +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 SightLine { + constructor(svg) { + this.svg = svg; + } + + getBoard() { + return this.svg.querySelector('.board'); + } + + getActiveHexes() { + return this.svg.querySelectorAll('use[href="#hex"].active'); + } + + clear() { + const board = this.getBoard(), + sl = board.querySelector('line.sight-line'), + target = board.querySelector(`use[href="#hex"].sight-line-target`); + + if (sl) { + sl.remove(); + } + + if (target) { + target.classList.remove('sight-line-target'); + } + + this.clearHexes(); + } + + clearHexes() { + if (this.distanceCallback) { + this.distanceCallback(); + } + + this.getActiveHexes().forEach(el => el.classList.remove('active')); + } + + draw(source, target) { + this.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); + + this.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); + } + + update(cell, { x, y }) { + const sl = this.svg.querySelector('.sight-line'), + target = this.svg.querySelector('.sight-line-target').parentElement, + x1 = cell.dataset.x, + y1 = cell.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))); + } + + drawHexes(...coords) { + this.clearHexes() + + if (this.distanceCallback) { + this.distanceCallback(offset_distance(...coords)); + } + + let lineCoords = linedraw(...coords); + + let s = lineCoords + .map(([x, y]) => `g[data-y="${y}"] g[data-x="${x}"] use[href="#hex"]`) + .join(', '); + + this.svg.querySelectorAll(s).forEach(p => p.classList.add('active')); + } +} |