import FiringArc from './firingArc.js';
const svgns = "http://www.w3.org/2000/svg";
function isEven(n) {
return n % 2 === 0;
}
function radToDeg(radians) {
return radians * 180 / Math.PI;
}
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;
placing = [];
#firingArcVisibility = {
davion: false,
liao: false
};
constructor(svg) {
this.svg = svg;
this.firingArc = new FiringArc(svg);
this.setUpSightLine(this);
this.setUpCounter(this);
this.setUpCells();
}
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);
}
}
select(allegiance, number) {
this.Counter.select({ dataset: { allegiance, number } });
}
unSelect() {
this.Counter.unSelect();
}
endTurn(allegiance) {
const selector = `#firing-arcs [data-troop-allegiance="${allegiance}"]`;
this.svg.querySelectorAll(selector).forEach(el => el.remove());
}
toggleProne() {
this.Counter.toggleProne();
}
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 => {
const toPlace = this.placing.pop();
// TODO
let existingOccupant =
this.svg.querySelector(`.counter[data-x="${point.dataset.x}"][data-y="${point.dataset.y}"]`);
if (toPlace && toPlace.getAttribute('href') === '#counter-grenade') {
point.parentElement.appendChild(toPlace);
return;
}
if (this.getSelected() && !existingOccupant) {
let sl = this.svg.querySelector('.sight-line');
this.placing.push(toPlace);
this.Counter.place(point);
if (sl) {
if (sl.classList.contains('active')) {
this.SightLine.clear();
} else {
this.SightLine.update(point);
}
}
}
});
// Logic for this event:
// If there's a locked sightline, unlock it. Otherwise, if there's an
// active sightline, lock it.
// There is an active sightline when there is a selected soldier, its
// counter is on the board, and the pointer is over a cell other than the
// one that counter occupies.
// There is a locked sightline when there is a selected soldier, its
// counter is on the board, and one cell has the 'sight-line-target' class.
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',
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);
}
container.proneFlagCallback(!!this.parentElement.querySelector('[href="#counter-prone"]'));
this.parentElement.appendChild(counter);
this.remove();
container.Counter.removeClones(counter);
trace.remove();
} else {
const proneCounter = this.parentElement.querySelector('[href="#counter-prone"]');
if (proneCounter) {
proneCounter.remove();
}
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);
}
const proneCounter = this.parentElement.querySelector('[href="#counter-prone"]');
if (proneCounter) {
proneCounter.remove();
}
container.proneFlagCallback(!!clone.parentElement.querySelector('[href="#counter-prone"]'));
clone.parentElement.appendChild(this);
clone.remove();
}
} else {
e.stopPropagation();
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) {
container.placing.push(counter);
counter.classList.add(selectedClass);
let existingArcs = container.getExistingArcs(allegiance, number);
existingArcs.forEach(el => el.removeAttribute('clip-path'));
container.selectCallback({ prone: this.hasProne(counter), ...counter.dataset });
}
};
this.unSelect = function () {
let selected = container.getSelected();
container.place = [];
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);
if (counter.parentElement.querySelector('[href="#counter-prone"]')) {
container.Counter.toggleProne();
}
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 => {
const proneCounter = el.parentElement.querySelector('[href="#counter-prone"]');
if (proneCounter) {
proneCounter.remove();
}
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 (counter) {
const isOnBoard = counter.parentElement.hasAttribute('data-x');
if (isOnBoard) {
return !!counter.parentElement.querySelector('[href="#counter-prone"]');
}
return false;
};
this.toggleProne = function() {
const selected = container.getSelected(),
isOnBoard = selected && selected.parentElement.hasAttribute('data-x');
if (selected && isOnBoard) {
const proneCounter = selected.parentElement.querySelector('[href="#counter-prone"]');
if (proneCounter) {
proneCounter.remove();
} else {
const counter = document.createElementNS(svgns, 'use');
counter.setAttributeNS(null, 'href', '#counter-prone');
selected.parentElement.appendChild(counter);
}
}
}
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 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.distanceCallback) {
ptGrp.distanceCallback();
}
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.distanceCallback) {
ptGrp.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(', ');
ptGrp.svg.querySelectorAll(s).forEach(p => p.classList.add('active'));
};
}
}
setFiringArc(size) {
const counter = this.getSelected();
if (counter) {
const { allegiance, number } = counter.dataset,
cellPosition = this.getCellPosition(counter.parentElement);
this.firingArc.set(size, allegiance, number, cellPosition);
}
}
setGrenade() {
let counter = document.createElementNS(svgns, 'use');
counter.setAttributeNS(null, 'href', '#counter-grenade');
counter.addEventListener('click', () => counter.remove());
this.placing.push(counter);
}
}