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 troopSelector(number, allegiance) {
return `[data-troop-number="${number}"][data-troop-allegiance="${allegiance}"]`;
}
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;
}
let getPointCoords = (x, y) => {
let point = document.querySelector(`[data-x="${x}"][data-y="${y}"]`);
return [point.x.baseVal.value, point.y.baseVal.value]
};
function positionFiringArc(e) {
let activeFiringArc = document.querySelector('polygon.firing-arc.active');
// TODO: handle exactly horizontal and vertical lines
if (activeFiringArc) {
let activeFiringArcOutline = document.querySelector(`#lines polygon[data-troop-number="${activeFiringArc.dataset.troopNumber}"][data-troop-allegiance="${activeFiringArc.dataset.troopAllegiance}"]`);
board = document.getElementById('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 = 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);
}
}
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;
}
const svgns = "http://www.w3.org/2000/svg",
svg = document.querySelector('svg'),
hex = document.getElementById('point'),
ptGrp = document.getElementById('points'),
cntrGrp = document.getElementById('counters'),
settingsPanel = document.getElementById('panel'),
recordSheetVisibility = document.querySelector('#content input[type="checkbox"].visible');
const q = s => document.querySelector(s),
qA = s => document.querySelectorAll(s);
const { x: VIEWBOX_X, y: VIEWBOX_Y, width: VIEWBOX_WIDTH, height: VIEWBOX_HEIGHT } =
svg.viewBox.baseVal;
const COLUMN_COUNT = 33,
ROW_COUNT = 51,
// const COLUMN_COUNT = 20,
// ROW_COUNT = 20,
HORZ_POINT_DISTANCE = 1.005,
VERT_POINT_DISTANCE = Math.sqrt(3) * HORZ_POINT_DISTANCE / 2,
ALTERNATING_OFFSET = HORZ_POINT_DISTANCE / 2,
CIRCUMRADIUS = Math.max(...[...new Set(Object.values(hex.points).flatMap(({x, y}) => [x, y]))]),
INRADIUS = CIRCUMRADIUS * Math.sqrt(3) / 2,
[COLUMNS, ROWS] = [COLUMN_COUNT, ROW_COUNT].map(n => [...Array(n).keys()]),
POINTS = ROWS.map(y => COLUMNS.map(x => [x, y]));
const FIRING_ARC_SIZE = {
'small': Math.atan(HORZ_POINT_DISTANCE / (6 * VERT_POINT_DISTANCE)),
'medium': Math.atan((HORZ_POINT_DISTANCE / 2) / VERT_POINT_DISTANCE),
'large': Math.atan((21 * HORZ_POINT_DISTANCE) / (6 * VERT_POINT_DISTANCE))
}
let prevVb = localStorage.getItem('viewBox');
let recVis = localStorage.getItem('recordsVisibility');
if (prevVb) {
svg.setAttributeNS(null, 'viewBox', prevVb);
}
if (recVis == 'false') {
recordSheetVisibility.checked = false;
}
let info = document.getElementById('status');
// Object.values(settingsPanel.querySelectorAll('fieldset')).forEach(fieldset => {
[].forEach(fieldset => {
const target = document.getElementById(fieldset.name);
const transform = getComputedStyle(target).transform.match(/-?\d+\.?\d*/g);
const inputs = fieldset.querySelectorAll('input');
if (transform) {
const [a, b, c, d, e, f] = transform.map(n => parseFloat(n));
// a c e
// b d f
const scaleX = Math.sqrt(a**2 + c**2);
const scaleY = Math.sqrt(b**2 + d**2);
let values = {
scale: Math.round(scaleX * 10) / 10,
translateX: e,
translateY: f,
rotate: Math.round(radToDeg((Math.acos(a / scaleX) + Math.asin(b / scaleY)) / 2) * 10) / 10
}
inputs.forEach(input => input.value = values[input.name]);
}
inputs.forEach(input => {
input.addEventListener('pointerenter', e => e.target.focus());
input.addEventListener('input', e => {
let { scale, translateX, translateY, rotate} = Object.values(inputs).reduce((acc, input) => {
acc[input.name] = input.value;
return acc;
}, {});
let transform = `translate(${translateX}px, ${translateY}px) rotate(${rotate}deg) scale(${scale})`;
target.style.transform = transform;
});
input.addEventListener('pointerleave', () => document.activeElement.blur());
});
});
function ptGrpToSvgPt(x, y) {
let transProp = getComputedStyle(ptGrp).transform.match(/-?\d+\.?\d*/g),
mtx = new DOMMatrix(transProp || ''),
pt = new DOMPoint(x, y),
svgP = pt.matrixTransform(mtx);
return svgP;
}
const Counter = new function() {
let container = cntrGrp,
selectedClass = 'selected',
dataSelector = function(troopNumber, allegiance) {
return `[data-troop-number="${troopNumber}"][data-troop-allegiance="${allegiance}"]`;
},
selector = function(troopNumber, allegiance) {
return `use${dataSelector(troopNumber, allegiance)}`;
},
traceSelector = function(troopNumber, allegiance) {
return `polyline.move-trace${dataSelector(troopNumber, allegiance)}`;
},
clickClone = function() {
let { troopNumber, troopAllegiance, x, y } = this.dataset,
xAttr = this.getAttribute('x'),
yAttr = this.getAttribute('y');
if (Counter.isSelected(troopNumber, troopAllegiance)) {
let trace = container.querySelector(traceSelector(troopNumber, troopAllegiance)),
points = trace.getAttribute('points').split(' ');
if (`${xAttr},${yAttr}` == points.at(0)) {
let counter = Counter.get(troopNumber, troopAllegiance);
counter.setAttributeNS(null, 'x', xAttr);
counter.setAttributeNS(null, 'y', yAttr);
counter.dataset.x = x;
counter.dataset.y = y;
container.querySelectorAll(`${selector(troopNumber, troopAllegiance)}.clone`).forEach(el => el.remove());
trace.remove();
} else {
points = points.filter(p => p != `${xAttr},${yAttr}`).join(' ');
trace.setAttributeNS(null, 'points', points);
}
this.remove();
}
};
this.get = function(troopNumber, allegiance) {
return container.querySelector(`${selector(troopNumber, allegiance)}:not(.clone)`);
};
this.select = function({ dataset: { troopNumber, troopAllegiance }}) {
this.unSelect();
let queriedCounter = container.querySelector(selector(troopNumber, troopAllegiance));
if (queriedCounter) {
queriedCounter.classList.add(selectedClass);
}
};
this.unSelect = function() {
container
.querySelectorAll(`.${selectedClass}`)
.forEach(el => el.classList.remove(selectedClass));
};
this.isSelected = function(troopNumber, allegiance) {
return container.querySelector(`${selector(troopNumber, allegiance)}.${selectedClass}`) !== null;
};
this.place = function({ dataset: { troopNumber, troopAllegiance }}, point) {
let tempSelector = selector(troopNumber, troopAllegiance);
new function() {
let counter, points,
selector = tempSelector,
counterNodeList = container.querySelectorAll(`${selector}`);
if (counterNodeList.length > 0) {
let counters = Array.from(counterNodeList),
original = counters.find(el => !el.classList.contains('clone')),
count = counters.filter(el => el.classList.contains('clone')).length,
trace = container.querySelector(traceSelector(troopNumber, troopAllegiance));
let current = {
x: point.dataset.x,
y: point.dataset.y,
xAttr: point.getAttribute('x'),
yAttr: point.getAttribute('y')
},
previous = {
x: original.dataset.x,
y: original.dataset.y,
xAttr: original.getAttribute('x'),
yAttr: original.getAttribute('y')
}
counter = original.cloneNode();
counter.setAttributeNS(null, 'x', previous.xAttr);
counter.setAttributeNS(null, 'y', previous.yAttr);
counter.dataset.x = previous.x;
counter.dataset.y = previous.y;
counter.dataset.cloneOrder = count + 1;
counter.classList.remove(selectedClass);
counter.classList.add('clone');
original.setAttributeNS(null, 'x', current.xAttr);
original.setAttributeNS(null, 'y', current.yAttr);
original.dataset.x = current.x;
original.dataset.y = current.y;
if (!trace) {
trace = document.createElementNS(svgns, 'polyline');
points = `${previous.xAttr},${previous.yAttr} ${current.xAttr},${current.yAttr}`;
trace.dataset.troopNumber = troopNumber;
trace.dataset.troopAllegiance = troopAllegiance;
trace.classList.add('move-trace');
container.prepend(trace);
} else {
points = `${trace.getAttribute('points')} ${current.xAttr},${current.yAttr}`;
}
trace.setAttributeNS(null, 'points', points);
counter.addEventListener('click', clickClone);
} else {
counter = document.createElementNS(svgns, 'use'),
counter.setAttributeNS(null, 'href', `#t-${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.addEventListener('dblclick', e => {
// let selectedSoldier = document.querySelector('.soldier-record.selected');
// if (selectedSoldier) {
// let trace = container.querySelector(`polyline.move-trace${selector}`);
// if (!trace) {
// let {troopNumber, troopAllegiance} = selectedSoldier.dataset,
// selector = troopSelector(troopNumber, troopAllegiance),
// targetIsSelectedSoldier = [
// e.target.dataset.troopNumber == troopNumber,
// e.target.dataset.troopAllegiance == troopAllegiance
// ].every(el => el);
// if (targetIsSelectedSoldier) {
// container.querySelectorAll(`${selector}`).forEach(el => el.remove());
// document.querySelectorAll(`#firing-arcs ${selector}`).forEach(el => el.remove());
// }
// }
// }
// });
// counter.addEventListener('click', e => {
// let selectedSoldier = document.querySelector('.soldier-record.selected');
// if (selectedSoldier) {
// let { troopNumber, troopAllegiance } = selectedSoldier.dataset,
// selector = troopSelector(troopNumber, troopAllegiance);
// if (counter.dataset.troopAllegiance == troopAllegiance && counter.dataset.troopNumber == troopNumber) {
// let trace = container.querySelector(`polyline.move-trace${selector}`);
// if (trace) {
// let points = trace.getAttribute('points').split(' ');
// let [xAttr, yAttr] = points.at(-2).split(',');
// let clone = container.querySelector(`${selector}[x="${xAttr}"][y="${yAttr}"].clone`);
// points.pop()
// if (points.length >= 2) {
// trace.setAttributeNS(null, 'points', points.join(' '));
// } else {
// trace.remove();
// }
// counter.setAttributeNS(null, 'x', clone.getAttribute('x'));
// counter.setAttributeNS(null, 'y', clone.getAttribute('y'));
// counter.dataset.x = clone.dataset.x;
// counter.dataset.y = clone.dataset.y;
// clone.remove();
// }
// }
// }
// });
}
container.appendChild(counter);
}
}
};
POINTS.forEach((row, index) => row.forEach(([x, y]) => {
var cx = x * INRADIUS * 2 + (isEven(index) ? INRADIUS : 0),
cy = y * 3 / 2 * CIRCUMRADIUS,
point = document.createElementNS(svgns, 'use');
cx = parseFloat(cx.toFixed(1));
cy = parseFloat(cy.toFixed(1));
point.setAttributeNS(null, 'href', `#point`);
point.setAttributeNS(null, 'x', cx);
point.setAttributeNS(null, 'y', cy);
point.dataset.x = x;
point.dataset.y = y;
point.addEventListener('click', e => {
let selectedSoldier = document.querySelector('.soldier-record.selected');
let existingOccupant =
svg.querySelector(`.counter[data-x="${point.dataset.x}"][data-y="${point.dataset.y}"]`);
if (selectedSoldier && !existingOccupant) {
Counter.place(selectedSoldier, point);
// let counter, points,
// { troopNumber, troopAllegiance } = selectedSoldier.dataset,
// selector = troopSelector(troopNumber, troopAllegiance),
// counterNodeList = cntrGrp.querySelectorAll(`use${selector}`);
// if (counterNodeList.length > 0) {
// let counters = Array.from(counterNodeList),
// original = counters.find(el => !el.classList.contains('clone')),
// count = counters.filter(el => el.classList.contains('clone')).length,
// trace = cntrGrp.querySelector(`polyline.move-trace${selector}`);
// let current = {
// x: point.dataset.x,
// y: point.dataset.y,
// xAttr: point.getAttribute('x'),
// yAttr: point.getAttribute('y')
// },
// previous = {
// x: original.dataset.x,
// y: original.dataset.y,
// xAttr: original.getAttribute('x'),
// yAttr: original.getAttribute('y')
// }
// counter = original.cloneNode();
// counter.setAttributeNS(null, 'x', previous.xAttr);
// counter.setAttributeNS(null, 'y', previous.yAttr);
// counter.dataset.x = previous.x;
// counter.dataset.y = previous.y;
// counter.dataset.cloneOrder = count + 1;
// counter.classList.add('clone');
// original.setAttributeNS(null, 'x', current.xAttr);
// original.setAttributeNS(null, 'y', current.yAttr);
// original.dataset.x = current.x;
// original.dataset.y = current.y;
// if (!trace) {
// trace = document.createElementNS(svgns, 'polyline');
// points = `${previous.xAttr},${previous.yAttr} ${current.xAttr},${current.yAttr}`;
// trace.dataset.troopNumber = troopNumber;
// trace.dataset.troopAllegiance = troopAllegiance;
// trace.classList.add('move-trace');
// cntrGrp.prepend(trace);
// } else {
// points = `${trace.getAttribute('points')} ${current.xAttr},${current.yAttr}`;
// }
// trace.setAttributeNS(null, 'points', points);
// counter.addEventListener('click', e => {
// let selectedSoldier = document.querySelector('.soldier-record.selected');
// if (selectedSoldier) {
// let { troopNumber, troopAllegiance } = selectedSoldier.dataset,
// selector = troopSelector(troopNumber, troopAllegiance);
// if (counter.dataset.troopAllegiance == troopAllegiance && counter.dataset.troopNumber == troopNumber) {
// let [xAttr, yAttr] = [counter.getAttribute('x'), counter.getAttribute('y')];
// let points = trace.getAttribute('points').split(' ');
// if (`${xAttr},${yAttr}` == points.at(0)) {
// original.setAttributeNS(null, 'x', xAttr);
// original.setAttributeNS(null, 'y', yAttr);
// original.dataset.x = counter.dataset.x;
// original.dataset.y = counter.dataset.y;
// cntrGrp.querySelectorAll(`use${selector}.clone`).forEach(el => el.remove());
// trace.remove();
// } else {
// let points = trace.getAttribute('points').split(' ').filter(p => p != `${xAttr},${yAttr}`);
// trace.setAttributeNS(null, 'points', points.join(' '));
// }
// counter.remove();
// }
// }
// });
// } else {
// counter = document.createElementNS(svgns, 'use'),
// counter.setAttributeNS(null, 'href', `#t-${troopNumber}`);
// counter.classList.add('counter');
// counter.setAttributeNS(null, 'x', cx);
// counter.setAttributeNS(null, 'y', cy);
// counter.dataset.troopNumber = troopNumber;
// counter.dataset.troopAllegiance = troopAllegiance;
// counter.dataset.x = point.dataset.x;
// counter.dataset.y = point.dataset.y;
// counter.addEventListener('dblclick', e => {
// let selectedSoldier = document.querySelector('.soldier-record.selected');
// if (selectedSoldier) {
// let trace = cntrGrp.querySelector(`polyline.move-trace${selector}`);
// if (!trace) {
// let {troopNumber, troopAllegiance} = selectedSoldier.dataset,
// selector = troopSelector(troopNumber, troopAllegiance),
// targetIsSelectedSoldier = [
// e.target.dataset.troopNumber == troopNumber,
// e.target.dataset.troopAllegiance == troopAllegiance
// ].every(el => el);
// if (targetIsSelectedSoldier) {
// cntrGrp.querySelectorAll(`${selector}`).forEach(el => el.remove());
// document.querySelectorAll(`#firing-arcs ${selector}`).forEach(el => el.remove());
// }
// }
// }
// });
// counter.addEventListener('click', e => {
// let selectedSoldier = document.querySelector('.soldier-record.selected');
// if (selectedSoldier) {
// let { troopNumber, troopAllegiance } = selectedSoldier.dataset,
// selector = troopSelector(troopNumber, troopAllegiance);
// if (counter.dataset.troopAllegiance == troopAllegiance && counter.dataset.troopNumber == troopNumber) {
// let trace = cntrGrp.querySelector(`polyline.move-trace${selector}`);
// if (trace) {
// let points = trace.getAttribute('points').split(' ');
// let [xAttr, yAttr] = points.at(-2).split(',');
// let clone = cntrGrp.querySelector(`${selector}[x="${xAttr}"][y="${yAttr}"].clone`);
// points.pop()
// if (points.length >= 2) {
// trace.setAttributeNS(null, 'points', points.join(' '));
// } else {
// trace.remove();
// }
// counter.setAttributeNS(null, 'x', clone.getAttribute('x'));
// counter.setAttributeNS(null, 'y', clone.getAttribute('y'));
// counter.dataset.x = clone.dataset.x;
// counter.dataset.y = clone.dataset.y;
// clone.remove();
// }
// }
// }
// });
// }
// cntrGrp.appendChild(counter);
}
});
point.addEventListener('mouseover', e => {
let selectedSoldier = document.querySelector('.soldier-record.selected');
if (selectedSoldier) {
// e.target.classList.add('active');
let { troopNumber: tn, troopAllegiance: ta } = selectedSoldier.dataset;
// let counter = svg.querySelector(`circle.counter[data-troop-number="${tn}"][data-troop-allegiance="${ta}"]`);
let counter = Counter.get(tn, ta);
let sl = svg.querySelector('.sight-line');
if (counter && (!sl || sl.classList.contains('active'))) {
if (sl) {
info.querySelector('#hex-count').textContent = '-';
info.style.display = 'none';
ptGrp.querySelectorAll('.active').forEach(el => el.removeAttribute('class'));
svg.querySelectorAll('.sight-line').forEach(el => el.remove());
}
let source = ptGrp.querySelector(`use[data-x="${counter.dataset.x}"][data-y="${counter.dataset.y}"]`);
let [x1, y1] = [source.x.baseVal.value, source.y.baseVal.value];
let [x2, y2] = [e.target.x.baseVal.value, e.target.y.baseVal.value];
if (x1 !== x2 || y1 !== y2) {
let { x: svgX1, y: svgY1 } = ptGrpToSvgPt(x1, y1);
let { x: svgX2, y: svgY2 } = ptGrpToSvgPt(x2, y2);
let sightLine = document.createElementNS(svgns, 'line');
sightLine.classList.add('sight-line');
sightLine.classList.add('active');
sightLine.setAttributeNS(null, 'x1', svgX1);
sightLine.setAttributeNS(null, 'y1', svgY1);
sightLine.setAttributeNS(null, 'x2', svgX2);
sightLine.setAttributeNS(null, 'y2', svgY2);
// svg.insertBefore(sightLine, ptGrp);
document.getElementById('grid').appendChild(sightLine);
let coords = [
counter.dataset.x,
counter.dataset.y,
e.target.dataset.x,
e.target.dataset.y
].map(n => parseInt(n));
info.querySelector('#hex-count').textContent = offset_distance(...coords);
info.style.display = 'block';
let lineCoords = linedraw(...coords);
lineCoords.shift();
let s = lineCoords.map(([x, y]) => `use[data-x="${x}"][data-y="${y}"]`).join(', ');
ptGrp.querySelectorAll(s).forEach(p => p.classList.add('active'));
}
}
}
});
// point.addEventListener('mouseout', e => {
// let sl = svg.querySelector('.sight-line.active');
// if (sl) {
// info.querySelector('#hex-count').textContent = '-';
// info.style.display = 'none';
// ptGrp.querySelectorAll('.active').forEach(el => el.removeAttribute('class'));
// svg.querySelectorAll('.sight-line').forEach(el => el.remove());
// }
// });
point.addEventListener('click', e => {
let sl = svg.querySelector('.sight-line');
if (sl) {
sl.classList.toggle('active');
if (sl.classList.contains('active')) {
point.dispatchEvent(new MouseEvent('mouseout'));
point.dispatchEvent(new MouseEvent('mouseover'));
}
}
});
ptGrp.appendChild(point);
// text = document.createElementNS(svgns, 'text'),
// text.setAttributeNS(null, 'x', cx);
// text.setAttributeNS(null, 'y', cy);
// text.textContent = `${point.dataset.x},${point.dataset.y}`;
// ptGrp.appendChild(text);
}));
document.querySelectorAll('.soldier-record').forEach(el =>
el.addEventListener('click', e => {
if (el.classList.contains('selected')) {
el.classList.remove('selected');
Counter.unSelect();
} else {
document.querySelectorAll('.soldier-record.selected').forEach(el =>
el.classList.remove('selected')
);
el.classList.add('selected');
Counter.select(el);
}
let sl = svg.querySelector('.sight-line');
if (sl) {
info.querySelector('#hex-count').textContent = '-';
info.style.display = 'none';
ptGrp.querySelectorAll('.active').forEach(el => el.removeAttribute('class'));
svg.querySelectorAll('.sight-line').forEach(el => el.remove());
}
})
);
document.querySelectorAll('.set-firing-arc').forEach(el => el.addEventListener('click', e => {
let selectedSoldier = document.querySelector('.soldier-record.selected');
if (selectedSoldier) {
let {troopNumber, troopAllegiance} = selectedSoldier.dataset;
let existingArcs = document.querySelectorAll(
`#firing-arcs [data-troop-number="${troopNumber}"][data-troop-allegiance="${troopAllegiance}"]`
);
existingArcs.forEach(el => el.remove());
let counter = document.querySelector(
`circle.counter[data-troop-number="${troopNumber}"][data-troop-allegiance="${troopAllegiance}"]`
);
if (counter) {
let arcLayer = document.getElementById('shapes');
let outlineLayer = document.getElementById('lines');
let grid = document.getElementById('grid');
const transform = getComputedStyle(grid).transform.match(/-?\d+\.?\d*/g);
const pt = new DOMPoint(counter.cx.baseVal.value, counter.cy.baseVal.value);
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 = e.target.dataset.size;
firingArc.setAttributeNS(null, 'points', `${pivotPoint} ${pivotPoint} ${pivotPoint}`);
firingArcOutline.dataset.troopNumber = troopNumber;
firingArcOutline.dataset.troopAllegiance = troopAllegiance;
firingArcOutline.setAttributeNS(null, 'points', `${pivotPoint} ${pivotPoint} ${pivotPoint}`);
arcLayer.appendChild(firingArc);
outlineLayer.appendChild(firingArcOutline);
let firingArcPlacementListener = e => {
document.querySelectorAll('.firing-arc.active').forEach(el => el.classList.remove('active'));
svg.removeEventListener('click', firingArcPlacementListener);
svg.removeEventListener('mousemove', positionFiringArc);
};
svg.addEventListener('mousemove', positionFiringArc);
svg.addEventListener('click', firingArcPlacementListener);
}
}
}));
svg.addEventListener('wheel', e => {
e.preventDefault();
const pt = new DOMPoint(e.clientX, e.clientY),
svgP = pt.matrixTransform(svg.getScreenCTM().inverse());
let { x, y, width, height } = svg.viewBox.baseVal,
widthDelta = width * 0.25,
heightDelta = height * 0.25,
xChange = (svgP.x - x) / width * widthDelta,
yChange = (svgP.y - y) / height * heightDelta,
widthChange = (1 - ((svgP.x - x) / width)) * widthDelta,
heightChange = (1 - ((svgP.y - y) / height)) * heightDelta,
newX = parseInt(e.deltaY < 0 ? x + xChange : x - xChange),
newWidth = parseInt(e.deltaY < 0 ? width - xChange - widthChange : width + xChange + widthChange),
newY = parseInt(e.deltaY < 0 ? y + yChange : y - yChange),
newHeight = parseInt(e.deltaY < 0 ? height - yChange - heightChange : height + yChange + heightChange);
let vb = `${newX} ${newY} ${newWidth} ${newHeight}`
localStorage.setItem('viewBox', vb);
svg.setAttributeNS(null, 'viewBox', vb);
});
ptGrp.addEventListener('mouseout', e => {
let sl = svg.querySelector('.sight-line');
if (sl && sl.classList.contains('active')) {
info.querySelector('#hex-count').textContent = '-';
info.style.display = 'none';
ptGrp.querySelectorAll('.active').forEach(el => el.removeAttribute('class'));
svg.querySelectorAll('.sight-line').forEach(el => el.remove());
}
});
svg.addEventListener('pointerdown', e => {
const minPanDistanceThreshold = 5;
let dist, ctm,
pan = false,
{ x, y, width, height } = svg.viewBox.baseVal,
startPt = new DOMPoint(e.clientX, e.clientY),
movePt = new DOMPoint();
function pointerMove(e) {
movePt.x = e.clientX;
movePt.y = e.clientY;
dist = Math.sqrt((movePt.x - startPt.x)**2 + (movePt.y - startPt.y)**2);
if (!pan && dist >= minPanDistanceThreshold) {
pan = true;
startPt.x = e.clientX;
startPt.y = e.clientY;
}
if (pan) {
svg.setPointerCapture(e.pointerId);
ctm = svg.getScreenCTM().inverse();
const [svgStartPt, svgMovePt] = [startPt, movePt].map(p => p.matrixTransform(ctm)),
moveX = parseInt(svgStartPt.x - svgMovePt.x + x),
moveY = parseInt(svgStartPt.y - svgMovePt.y + y);
let vb = `${moveX} ${moveY} ${width} ${height}`;
localStorage.setItem('viewBox', vb);
svg.setAttributeNS(null, 'viewBox', vb);
}
}
function pointerUp(e) {
svg.releasePointerCapture(e.pointerId);
svg.removeEventListener('pointermove', pointerMove);
svg.removeEventListener('pointerup', pointerUp);
}
svg.addEventListener('pointermove', pointerMove);
svg.addEventListener('pointerup', pointerUp);
});
// svg.addEventListener('pointermove', e => {
// if (e.target.classList.contains('counter')) {
// let p = svg.querySelector(`use[data-x="${e.target.dataset.x}"][data-y="${e.target.dataset.y}"]`);
// p.classList.add('hover');
// p.dispatchEvent(new MouseEvent('mouseover'));
// let removeHover = e => {
// p.classList.remove('hover');
// e.target.removeEventListener('pointerout', removeHover);
// };
// e.target.addEventListener('pointerout', removeHover);
// }
// });
recordSheetVisibility.addEventListener('input', e => {
localStorage.setItem('recordsVisibility', recordSheetVisibility.checked);
});
document.querySelectorAll('.end-move').forEach(el => el.addEventListener('click', e => {
let selectedSoldier = document.querySelector('.soldier-record.selected');
if (selectedSoldier) {
let { troopNumber, troopAllegiance } = selectedSoldier.dataset;
let selector = troopSelector(troopNumber, troopAllegiance);
let trace = cntrGrp.querySelector(`polyline.move-trace${selector}`);
if (trace) {
trace.remove();
}
counterNodeList = cntrGrp.querySelectorAll(`use.counter.clone${selector}`);
counterNodeList.forEach(el => el.remove());
selectedSoldier.classList.toggle('selected');
selectedSoldier.classList.toggle('movement-ended');
}
}));
let endTurnButtons = document.querySelectorAll('.end-turn');
let [al1, al2] = Array.from(endTurnButtons).map(el => el.dataset.allegiance);
endTurnButtons.forEach(el =>
el.addEventListener('click', ({target: {dataset: {allegiance}}}) => {
let al = allegiance == al1 ? al2 : al1;
qA(`#firing-arcs [data-troop-allegiance="${al}"]`).forEach(el => el.remove());
qA(`.soldier-record[data-troop-allegiance="${al}"]`).forEach(el =>
el.classList.remove('movement-ended')
);
let selected = q(`.soldier-record.selected`);
if (selected) {
selected.classList.remove('selected');
}
q(`.soldier-record[data-troop-allegiance="${al}"]`).classList.add('selected');
})
);
(function debug() {
function drawLine(x1, y1, x2, y2) {
let start = ptGrp.querySelector(`[data-x="${x1}"][data-y="${y1}"]`);
let end = ptGrp.querySelector(`[data-x="${x2}"][data-y="${y2}"]`);
let [startX, startY] = [start.x.baseVal.value, start.y.baseVal.value];
let [endX, endY] = [end.x.baseVal.value, end.y.baseVal.value];
let startP = new DOMPoint(startX, startY);
let endP = new DOMPoint(endX, endY);
let tStart = startP.matrixTransform(mtx);
let tEnd = endP.matrixTransform(mtx);
let line = document.createElementNS(svgns, 'line');
line.setAttributeNS(null, 'x1', tStart.x);
line.setAttributeNS(null, 'y1', tStart.y);
line.setAttributeNS(null, 'x2', tEnd.x);
line.setAttributeNS(null, 'y2', tEnd.y);
line.classList.add('debug');
line.setAttributeNS(null, 'stroke', 'gold');
line.setAttributeNS(null, 'stroke-width', 2);
svg.appendChild(line);
return line;
}
let transProp = getComputedStyle(ptGrp).transform.match(/-?\d+\.?\d*/g),
mtx = new DOMMatrix(transProp || ''),
circR = (new DOMPoint(0, 3 * CIRCUMRADIUS / 2)).matrixTransform(mtx).y * 2 / 3;
})();