540 lines
17 KiB
JavaScript
540 lines
17 KiB
JavaScript
import * as firingArc from './game/firing_arc.js';
|
|
import * as sightLine from './game/sight_line.js';
|
|
import * as soldier from './game/soldier.js';
|
|
import { Observable } from "./observable";
|
|
|
|
let svg,
|
|
placing = [];
|
|
|
|
const top = {
|
|
collection: new Map()
|
|
};
|
|
|
|
function getCellContents(cell) {
|
|
return cell.querySelectorAll('*:not(use[href="#hex"])');
|
|
}
|
|
|
|
function getGridIndex({ parentElement: { dataset: { q, r, s, t }}}) {
|
|
return { q: +q, r: +r, s: +s, t: +t };
|
|
}
|
|
|
|
function getHex(cell) {
|
|
return cell.querySelector('use[href="#hex"]');
|
|
}
|
|
|
|
function getCellOccupant(cell) {
|
|
return cell.querySelector('.counter') || svg.querySelector('.grid-top .counter');
|
|
}
|
|
|
|
function getCells(svg) {
|
|
return svg.querySelectorAll('[data-q][data-r][data-s][data-t]');
|
|
}
|
|
|
|
function getLockedSightLine(svg) {
|
|
return svg.querySelector('line.sight-line:not(.active)');
|
|
}
|
|
|
|
function getActiveSightLine(svg) {
|
|
return svg.querySelector('line.sight-line.active');
|
|
}
|
|
|
|
function isCounter(el) {
|
|
const regex = new RegExp('^#counter-')
|
|
return el && regex.test(el.getAttribute('href'));
|
|
}
|
|
|
|
function isMechTemplate(el) {
|
|
return el && el.getAttribute('class') === 'mech-template';
|
|
}
|
|
|
|
function isClone(counter) {
|
|
const isClone = counter.classList.contains('clone'),
|
|
{ allegiance: clAl, number: clNum } = counter.dataset;
|
|
|
|
return {
|
|
of: function ({ dataset: { allegiance, number }}) {
|
|
return isClone && clAl == allegiance && clNum == number;
|
|
}
|
|
};
|
|
}
|
|
|
|
function getCellPosition(cell) {
|
|
const [x, y] = cell.getAttributeNS(null, 'transform').match(/-?\d+\.?\d*/g);
|
|
|
|
return { x, y };
|
|
}
|
|
|
|
function getCell(q, r, s, t) {
|
|
return svg.querySelector(`g[data-q="${q}"][data-r="${r}"][data-s="${s}"][data-t="${t}"]`);
|
|
}
|
|
|
|
function getCounterAtGridIndex(...coords) {
|
|
return getCell(...coords).querySelector('.counter');
|
|
}
|
|
|
|
function getSelected() {
|
|
return svg.querySelector(`.counter.selected[data-allegiance][data-number]`);
|
|
}
|
|
|
|
function deselect() {
|
|
const selected = getSelected();
|
|
placing = [];
|
|
|
|
if (selected) {
|
|
selected.classList.remove(soldier.getSelectedClass());
|
|
clearSightLine();
|
|
firingArc.clipAll(svg);
|
|
}
|
|
}
|
|
|
|
function clearSightLine() {
|
|
sightLine.setHexes([]);
|
|
sightLine.clear();
|
|
Observable.notify('distance');
|
|
}
|
|
|
|
function calcSightLineIndexes(source, target) {
|
|
const { q: sq, r: sr, s: ss } = source.dataset;
|
|
const { q: tq, r: tr, s: ts } = target.dataset;
|
|
const sourceIndex = { q: +sq, r: +sr, s: +ss };
|
|
const targetIndex = { q: +tq, r: +tr, s: +ts };
|
|
|
|
return sightLine.calcIndexes(sourceIndex, targetIndex);
|
|
}
|
|
|
|
function getSightLineHexes(indexes) {
|
|
const selector = indexes
|
|
.map(({ q, r, s }) => `g[data-q="${q}"][data-r="${r}"][data-s="${s}"] use[href="#hex"]`)
|
|
.join(', ');
|
|
|
|
return svg.querySelectorAll(selector);
|
|
}
|
|
|
|
function calcSightLine(source, target) {
|
|
const indexes = calcSightLineIndexes(source, target);
|
|
const hexes = getSightLineHexes(indexes);
|
|
sightLine.setHexes(hexes);
|
|
Observable.notify('distance', indexes.length - 1);
|
|
}
|
|
|
|
function updateSightLine(cell) {
|
|
calcSightLine(cell, sightLine.getLockTarget());
|
|
sightLine.update(getCellPosition(cell));
|
|
}
|
|
|
|
function drawSightLine(sourceCell, targetCell) {
|
|
calcSightLine(sourceCell, targetCell)
|
|
const line = sightLine.create(getCellPosition(sourceCell), getCellPosition(targetCell));
|
|
svg.querySelector('.gameboard').appendChild(line);
|
|
}
|
|
|
|
function moveBackOneStepInHistory(counter) {
|
|
const trace = soldier.getTrace(svg, counter);
|
|
|
|
counter.remove();
|
|
counter = getCounterAtGridIndex(...counter.dataset.previous.split(','));
|
|
counter.classList.remove('clone');
|
|
counter.classList.add(soldier.getSelectedClass());
|
|
|
|
if (!('previous' in counter.dataset)) {
|
|
trace.remove();
|
|
} else {
|
|
const points = trace.getAttribute('points').split(' ');
|
|
points.pop();
|
|
trace.setAttributeNS(null, 'points', points.join(' '));
|
|
}
|
|
|
|
return counter;
|
|
}
|
|
|
|
function clearMoveHistory(clone, counter) {
|
|
clone.classList.remove('clone');
|
|
clone.classList.add(soldier.getSelectedClass());
|
|
counter.remove();
|
|
counter = clone;
|
|
soldier.removeClones(svg, counter);
|
|
soldier.getTrace(svg, counter).remove();
|
|
|
|
return counter;
|
|
}
|
|
|
|
function deleteClone(occupant, counter, cell) {
|
|
const index = getGridIndex(occupant),
|
|
trace = soldier.getTrace(svg, counter),
|
|
pos = getCellPosition(cell),
|
|
points = trace.getAttribute('points').split(' ').filter(p => p != `${pos.x},${pos.y}`).join(' ');;
|
|
|
|
let current = counter;
|
|
trace.setAttributeNS(null, 'points', points);
|
|
|
|
while (current.dataset.previous != `${index.q},${index.r},${index.s},${index.t}`) {
|
|
current = getCounterAtGridIndex(...current.dataset.previous.split(','));
|
|
}
|
|
|
|
current.dataset.previous = occupant.dataset.previous;
|
|
occupant.remove();
|
|
}
|
|
|
|
function hasPreviousMoveInHistory(counter) {
|
|
return 'previous' in counter.dataset;
|
|
}
|
|
|
|
function selectOffBoard() {
|
|
Observable.notify('select', this);
|
|
}
|
|
|
|
function select(data) {
|
|
const counter = data && (soldier.getCounter(svg, data) || soldier.createCounter(data));
|
|
const isSelected = data && data.classList && data.classList.contains('selected');
|
|
|
|
deselect();
|
|
|
|
if (isSelected || !data) return;
|
|
|
|
counter.classList.add(soldier.getSelectedClass());
|
|
firingArc.get(svg, counter).forEach(el => el.removeAttribute('clip-path'));
|
|
placing.push(counter);
|
|
}
|
|
|
|
function endMove() {
|
|
const selected = getSelected();
|
|
|
|
if (selected) {
|
|
soldier.endMove(svg, selected);
|
|
deselect();
|
|
}
|
|
}
|
|
|
|
export function start(el) {
|
|
svg = el;
|
|
const gridTop = svg.querySelector('.grid-top');
|
|
top.container = svg.querySelector('.grid-top > .container');
|
|
const topHex = svg.querySelector('.grid-top > use[href="#hex"]');
|
|
|
|
gridTop.addEventListener('pointerleave', e => {
|
|
// Work around webkit bug https://bugs.webkit.org/show_bug.cgi?id=233432
|
|
const elUnderCursor = svg.parentNode.elementFromPoint(e.clientX, e.clientY);
|
|
if (!e.target.contains(elUnderCursor)) {
|
|
console.log(['pointerleave', gridTop]);
|
|
[...top.container.children].forEach(child => {
|
|
top.collection.get(child).parent.append(child);
|
|
top.collection.delete(child);
|
|
});
|
|
|
|
top.cell = null;
|
|
}
|
|
});
|
|
|
|
topHex.addEventListener('click', clickHandler);
|
|
|
|
const startingLocations = svg.querySelector('.start-locations');
|
|
startingLocations && getUnits(startingLocations).forEach(unit => unit.addEventListener('click', selectOffBoard));
|
|
|
|
function clickHandler(e) {
|
|
console.log('top hex click event');
|
|
//const occupant = getCellOccupant(this);
|
|
const occupant = svg.querySelector('.grid-top .container .counter')
|
|
let toPlace = placing.pop();
|
|
|
|
if (isCounter(toPlace) || isMechTemplate(toPlace)) {
|
|
//getHex(this).after(toPlace);
|
|
top.collection.set(toPlace, { parent: top.cell });
|
|
top.container.append(toPlace);
|
|
//if (isCounter(toPlace)) arrangeCounters(this);
|
|
if (isCounter(toPlace)) arrangeCounters(top.container);
|
|
removeEventListener("keydown", handleMechTemplateRotation);
|
|
} else if (toPlace && !occupant) {
|
|
//soldier.place(svg, toPlace, this);
|
|
top.collection.set(toPlace, { parent: top.cell });
|
|
top.container.prepend(toPlace);
|
|
//toPlace.removeEventListener('click', selectOffBoard);
|
|
placing.push(toPlace);
|
|
//getLockedSightLine(svg) ? updateSightLine(this) : clearSightLine();
|
|
} else if (toPlace && occupant) {
|
|
if (toPlace === occupant) {
|
|
Observable.notify('select');
|
|
} else {
|
|
Observable.notify('select', occupant);
|
|
}
|
|
} else if (!toPlace && occupant) {
|
|
Observable.notify('select', occupant);
|
|
} else {
|
|
console.log(['removing this contents', this]);
|
|
getCellContents(this).forEach(el => el.remove());
|
|
}
|
|
|
|
const selected = getSelected();
|
|
}
|
|
|
|
getCells(svg).forEach(cell => {
|
|
cell.addEventListener('click', e => {
|
|
console.log('cell clickevent');
|
|
const occupant = getCellOccupant(cell);
|
|
let toPlace = placing.pop();
|
|
|
|
if (isCounter(toPlace) || isMechTemplate(toPlace)) {
|
|
//getHex(cell).after(toPlace);
|
|
top.collection.set(toPlace, { parent: cell });
|
|
top.container.append(toPlace);
|
|
//if (isCounter(toPlace)) arrangeCounters(cell);
|
|
if (isCounter(toPlace)) arrangeCounters(top.container);
|
|
removeEventListener("keydown", handleMechTemplateRotation);
|
|
} else if (toPlace && !occupant) {
|
|
soldier.place(svg, toPlace, cell);
|
|
toPlace.removeEventListener('click', selectOffBoard);
|
|
placing.push(toPlace);
|
|
getLockedSightLine(svg) ? updateSightLine(cell) : clearSightLine();
|
|
} else if (toPlace && occupant) {
|
|
if (toPlace === occupant) {
|
|
if (hasPreviousMoveInHistory(toPlace)) {
|
|
toPlace = moveBackOneStepInHistory(toPlace);
|
|
placing.push(toPlace);
|
|
getLockedSightLine(svg) ? updateSightLine(toPlace.parentElement) : drawSightLine(toPlace.parentElement, cell);
|
|
} else {
|
|
Observable.notify('select');
|
|
}
|
|
} else if (!occupant.classList.contains('clone')) {
|
|
Observable.notify('select', occupant);
|
|
} else {
|
|
if (isClone(occupant).of(toPlace)) {
|
|
if (hasPreviousMoveInHistory(occupant)) {
|
|
deleteClone(occupant, toPlace, cell);
|
|
} else {
|
|
toPlace = clearMoveHistory(occupant, toPlace);
|
|
getLockedSightLine(svg) ? updateSightLine(cell) : clearSightLine();
|
|
}
|
|
}
|
|
placing.push(toPlace);
|
|
}
|
|
} else if (!toPlace && occupant) {
|
|
Observable.notify('select', occupant);
|
|
} else {
|
|
console.log('removing cell contents', cell);
|
|
getCellContents(cell).forEach(el => el.remove());
|
|
}
|
|
|
|
const selected = getSelected();
|
|
});
|
|
|
|
cell.addEventListener('dblclick', e => {
|
|
const toPlace = placing.pop(),
|
|
occupant = getCellOccupant(cell);
|
|
|
|
if (toPlace && occupant && toPlace === occupant) {
|
|
const { number, allegiance } = toPlace.dataset,
|
|
selector = `[data-allegiance="${allegiance}"][data-number="${number}"]`;
|
|
|
|
svg.querySelectorAll(selector).forEach(el => el.remove());
|
|
Observable.notify('select');
|
|
}
|
|
});
|
|
|
|
cell.addEventListener('contextmenu', e => {
|
|
e.preventDefault();
|
|
|
|
sightLine.toggleLock(cell);
|
|
cell.dispatchEvent(new MouseEvent('pointerover'));
|
|
});
|
|
|
|
cell.addEventListener('pointerover', () => {
|
|
console.log(['pointerenter', cell]);
|
|
|
|
top.cell = cell;
|
|
|
|
[...top.container.children].forEach(child => {
|
|
top.collection.get(child).parent.append(child);
|
|
top.collection.delete(child);
|
|
});
|
|
|
|
top.container.parentElement.setAttributeNS(null, 'transform', cell.getAttributeNS(null, 'transform'));
|
|
|
|
[...cell.children].filter(c => c.getAttributeNS(null, 'href') !== '#hex').forEach(child => {
|
|
top.collection.set(child, { parent: cell });
|
|
top.container.append(child);
|
|
});
|
|
|
|
let occupant = svg.querySelector('.grid-top .container .counter');
|
|
const selected = getSelected();
|
|
|
|
if (placing[0]?.getAttributeNS(null, 'class') == 'mech-template') {
|
|
cell.appendChild(placing[0]);
|
|
}
|
|
|
|
if (selected && svg.querySelector('.grid').contains(selected) && !getLockedSightLine(svg) && cell !== selected.parentElement) {
|
|
clearSightLine();
|
|
drawSightLine(selected.parentElement, cell);
|
|
}
|
|
|
|
occupant = getCellOccupant(cell);
|
|
|
|
if (occupant) {
|
|
firingArc.toggleCounterVisibility(svg, occupant, true);
|
|
}
|
|
});
|
|
|
|
//cell.addEventListener('pointerout', e => {
|
|
// console.log('pointerout');
|
|
// If pointerout was not triggered by hovering over an element on that
|
|
// game hex
|
|
//if (!e.relatedTarget || top.collection.get(e.relatedTarget)?.parent !== cell) {
|
|
// [...top.container.children].forEach(child => {
|
|
// top.collection.get(child).parent.append(child);
|
|
// top.collection.delete(child);
|
|
// });
|
|
//
|
|
// cell.classList.remove('hover');
|
|
// getActiveSightLine(svg) && clearSightLine();
|
|
//
|
|
// const occupant = getCellOccupant(cell);
|
|
//
|
|
// if (occupant) {
|
|
// firingArc.toggleCounterVisibility(svg, occupant, false);
|
|
// }
|
|
//}
|
|
//});
|
|
});
|
|
|
|
//const cell = document.querySelector('[data-q="0"][data-r="0"][data-s="0"][data-t="0"]');
|
|
//const povr = new PointerEvent('pointerover');
|
|
//const pout = new PointerEvent('pointerout');
|
|
//cell.dispatchEvent(povr);
|
|
//cell.dispatchEvent(pout);
|
|
|
|
// debug //
|
|
// Add a trooper counter
|
|
const attacker = { dataset: { allegiance: 'attacker', number: 1, squad: 1 }};
|
|
// const defender = { dataset: { allegiance: 'defender', number: 1, squad: 2 }};
|
|
const cell = getCell(0, 0, 0, 0);
|
|
const trooper = soldier.createCounter(attacker, 'blazer');
|
|
//const trooperSack = document.createElementNS(svgns, 'g');
|
|
//trooperSack.classList.add('cell-contents');
|
|
//trooperSack.append(trooper);
|
|
soldier.place(svg, trooper, cell);
|
|
|
|
// Add some counters in an unoccupied cell
|
|
//const countersCell = getCell(-1, 1, 0, 0);
|
|
//setCounter('grenade');
|
|
//setCounter('prone');
|
|
//setCounter('1st-floor');
|
|
//const e = new PointerEvent('click');
|
|
//countersCell.dispatchEvent(e);
|
|
//countersCell.dispatchEvent(e);
|
|
//countersCell.dispatchEvent(e);
|
|
///////////
|
|
|
|
Observable.subscribe('select', select);
|
|
Observable.subscribe('endmove', endMove);
|
|
|
|
console.log('gameboard.js loaded');
|
|
}
|
|
|
|
export function stop() {
|
|
Observable.unsubscribe('select', select);
|
|
Observable.unsubscribe('endmove', endMove);
|
|
}
|
|
|
|
export function getUnits() {
|
|
return soldier.getAllCounters(svg);
|
|
}
|
|
|
|
export function clearFiringArcs(allegiance) {
|
|
firingArc.clear(svg, allegiance);
|
|
}
|
|
|
|
export function toggleFiringArcVisibility() {
|
|
firingArc.toggleVisibility(svg, this.dataset.allegiance);
|
|
}
|
|
|
|
export function setFiringArc() {
|
|
const counter = getSelected(),
|
|
isOnBoard = counter => counter && counter.parentElement.hasAttribute('data-q');
|
|
|
|
if (isOnBoard(counter)) {
|
|
returnToParent(top);
|
|
firingArc.set(svg, this.dataset.size, counter, getCellPosition(counter.parentElement));
|
|
}
|
|
}
|
|
|
|
export function setCounter(name) {
|
|
const selected = getSelected();
|
|
const counter = document.createElementNS(svgns, 'use');
|
|
|
|
counter.addEventListener('click', e => {
|
|
e.stopPropagation()
|
|
const container = counter.parentElement;
|
|
counter.remove()
|
|
arrangeCounters(container);
|
|
});
|
|
|
|
counter.setAttributeNS(null, 'href', `#counter-${name}`);
|
|
counter.classList.add(`counter-${name}`);
|
|
|
|
if (selected) {
|
|
selected.append(counter);
|
|
arrangeCounters(selected);
|
|
}
|
|
else
|
|
placing.push(counter);
|
|
}
|
|
|
|
function arrangeCounters(container) {
|
|
const counters = [...container.children].filter(isCounter);
|
|
const length = 12;
|
|
const gravity = 1;
|
|
const lateralForce = gravity;
|
|
const rads = Math.atan(lateralForce / gravity);
|
|
const bestFitCount = 8;
|
|
const deflection = counters.length > bestFitCount ? 2 * Math.PI / counters.length : Math.atan(lateralForce / gravity);
|
|
|
|
counters.forEach((counter, index, arr) => {
|
|
const mult = index - arr.length / 2 + 0.5;
|
|
const theta = deflection * mult;
|
|
const x = length * Math.sin(theta);
|
|
const y = length * Math.cos(theta);
|
|
counter.setAttributeNS(null, 'style', `--x: ${-x}px; --y: ${y}px`);
|
|
});
|
|
}
|
|
|
|
function handleMechTemplateRotation(event) {
|
|
const counter = placing[0];
|
|
const upper = placing[0].querySelector('use[href="#mech-template-upper"]');
|
|
|
|
if (event.key === 'a') {
|
|
let direction = +counter.style.transform.match(/-?\d+/) || 0;
|
|
direction -= 60;
|
|
counter.style.transform = `rotate(${direction}deg)`;
|
|
} else if (event.key === 'd') {
|
|
let direction = +counter.style.transform.match(/-?\d+/) || 0;
|
|
direction += 60;
|
|
counter.style.transform = `rotate(${direction}deg)`;
|
|
} else if (event.key === 'q') {
|
|
let facing = +upper.style.transform.match(/-?\d+/) || 0;
|
|
facing = facing <= -60 ? -60 : facing - 60;
|
|
upper.style.transform = `rotate(${facing}deg)`;
|
|
} else if (event.key === 'e') {
|
|
let facing = +upper.style.transform.match(/-?\d+/) || 0;
|
|
facing = facing >= 60 ? 60 : facing + 60;
|
|
upper.style.transform = `rotate(${facing}deg)`;
|
|
}
|
|
}
|
|
|
|
export function setMechTemplate() {
|
|
const counter = document.createElementNS(svgns, 'g');
|
|
counter.setAttributeNS(null, 'class', 'mech-template');
|
|
counter.style.pointerEvents = 'none';
|
|
counter.style.transition = 'transform 0.5s';
|
|
|
|
const lower = document.createElementNS(svgns, 'use');
|
|
lower.setAttributeNS(null, 'href', '#mech-template-lower');
|
|
|
|
const upper = document.createElementNS(svgns, 'use');
|
|
upper.setAttributeNS(null, 'href', '#mech-template-upper');
|
|
upper.style.transition = 'transform 0.5s';
|
|
|
|
counter.appendChild(lower);
|
|
counter.appendChild(upper);
|
|
|
|
addEventListener("keydown", handleMechTemplateRotation);
|
|
placing.push(counter);
|
|
}
|