Web Dev Solutions

Catalin Mititiuc

aboutsummaryrefslogtreecommitdiff
blob: d6059ae102aab8a15ad841799d5bfe636ccbbd64 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
import FiringArc from './firingArc.js';
import SightLine from './sightLine.js';
import Counter from './counter.js';

const svgns = "http://www.w3.org/2000/svg";

export default class Game {
  info;
  placing = [];

  #firingArcVisibility = {
    davion: false,
    liao: false
  };

  constructor(svg) {
    this.svg = svg;
    this.firingArc = new FiringArc(svg);
    this.sightLine = new SightLine(svg);
    this.counter = new Counter(svg);

    this.setUpCells();
  }

  getCells() {
    return this.svg.querySelectorAll('g[data-y] > g[data-x]');
  }

  getCell(x, y) {
    return this.svg.querySelector(`g[data-y="${y}"] > g[data-x="${x}"]`);
  }

  getCellOccupant(cell) {
    return cell.querySelector('.counter');
  }

  getCellContents(cell) {
    return cell.querySelectorAll('*:not(use[href="#hex"])');
  }

  getHex(cell) {
    return cell.querySelector('use[href="#hex"]');
  }

  getSelected() {
    return this.svg.querySelector(`.counter.selected[data-allegiance][data-number]`);
  }

  getSightLine() {
    return this.svg.querySelector('line.sight-line');
  }

  getExistingArcs(al, n) {
    return this.svg.querySelectorAll(`#firing-arcs polygon[data-number="${n}"][data-allegiance="${al}"]`);
  }

  getUnclippedFiringArcs() {
    return this.svg.querySelectorAll('#firing-arcs polygon:not([clip-path])');
  }

  getGridIndex({ parentElement: { dataset: { x }, parentElement: { dataset: { y }}}}) {
    return { x, y };
  }

  getCounterAtGridIndex(x, y) {
    return this.getCell(x, y).querySelector('.counter');
  }

  getBoard() {
    return this.svg.querySelector('.board');
  }

  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;
  }

  /**
   * @param {(count: [number]) => void} fn
   */
  set distanceCallback(fn) {
    this.sightLine.distanceCallback = fn;
  }

  endMove() {
    const selected = this.getSelected();

    if (selected) {
      this.counter.endMove(selected);
      this.unSelect();
    }
  }

  select({ dataset: { allegiance, number } }) {
    const counter = this.counter.getCounter(allegiance, number);

    if (counter) {
      this.unSelect();
      this.placing.push(counter);
      counter.classList.add(this.counter.selectedClass);
      this.getExistingArcs(allegiance, number).forEach(el => el.removeAttribute('clip-path'));
      this.selectCallback({ prone: this.counter.hasProne(counter), ...counter.dataset });
    }
  }

  unSelect() {
    const selected = this.getSelected();

    if (selected) {
      this.placing = [];
      this.getSelected().classList.remove(this.counter.selectedClass);
      this.sightLine.clear();
      this.clipFiringArcs();
    }
  }

  endTurn(allegiance) {
    const selector = `#firing-arcs [data-allegiance="${allegiance}"]`;
    this.svg.querySelectorAll(selector).forEach(el => el.remove());
  }

  toggleProne() {
    const selected = this.getSelected(),
      isOnBoard = selected && selected.parentElement.hasAttribute('data-x');

    if (selected && isOnBoard) {
      this.counter.toggleProne(selected);
    }
  }

  toggleFiringArcVisibility(allegiance) {
    const vis = this.#firingArcVisibility[allegiance],
      clipPaths = this.svg.querySelectorAll(`clipPath[data-allegiance="${allegiance}"]`);

    clipPaths.forEach(cp => cp.style.display = !vis ? 'none' : '');
    this.#firingArcVisibility[allegiance] = !vis;
  }

  clipFiringArcs() {
    let unclipped = this.getUnclippedFiringArcs();

    unclipped.forEach(el => {
      const { number, allegiance } = el.dataset,
        clipPathId = `clip-path-${allegiance}-${number}`,
        isVisible = this.#firingArcVisibility[allegiance];

      if (isVisible) {
        this.svg.querySelector(`#${clipPathId}`).style.display = 'none';
      }

      el.setAttributeNS(null, 'clip-path', `url(#${clipPathId})`);
    });
  }

  setUpCells() {
    this.getCells().forEach(cell => {
      function isGrenade(el) {
        return el && el.getAttribute('href') === '#counter-grenade';
      }

      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;
          }
        };
      }

      cell.addEventListener('click', e => {
        const state = {
          placing: this.placing,
          hex: cell.querySelector('use[href="#hex"]'),
          occupant: this.getCellOccupant(cell),
          contents: this.getCellContents(cell)
        };

        console.log(state);

        let toPlace = this.placing.pop();

        if (isGrenade(toPlace)) {
          state.hex.after(toPlace);
        } else if (toPlace && !state.occupant) {
          this.counter.place(toPlace, cell);
          this.placing.push(toPlace);
          const lockedSl = this.svg.querySelector('.sight-line:not(.active)');

          if (!lockedSl) {
            this.sightLine.clear();
          } else {
            this.sightLine.update(cell, this.getCellPosition(cell));
          }
        } else if (toPlace && state.occupant) {
          if (toPlace === state.occupant) {
            if ('previous' in toPlace.dataset) {
              const trace = this.counter.getTrace(toPlace);
              toPlace.remove();
              toPlace = this.getCounterAtGridIndex(...toPlace.dataset.previous.split(','));
              toPlace.classList.remove('clone');
              toPlace.classList.add(this.counter.selectedClass);
              if (!('previous' in toPlace.dataset)) {
                trace.remove();
              } else {
                const points = trace.getAttribute('points').split(' ');
                points.pop();
                trace.setAttributeNS(null, 'points', points.join(' '));
              }
              this.placing.push(toPlace);
              const lockedSl = this.svg.querySelector('.sight-line:not(.active)');

              if (!lockedSl) {
                this.sightLine.clear();
              } else {
                this.sightLine.update(toPlace.parentElement, this.getCellPosition(toPlace.parentElement));
              }
            } else {
              this.unSelect();
            }
          } else if (!state.occupant.classList.contains('clone')) {
            this.select(state.occupant);
          } else {
            if (isClone(state.occupant).of(toPlace)) {
              if (!('previous' in state.occupant.dataset)) {
                state.occupant.classList.remove('clone');
                state.occupant.classList.add(this.counter.selectedClass);
                toPlace.remove();
                toPlace = state.occupant;
                this.counter.removeClones(toPlace);
                this.counter.getTrace(toPlace).remove();
                const lockedSl = this.svg.querySelector('.sight-line:not(.active)');

                if (!lockedSl) {
                  this.sightLine.clear();
                } else {
                  this.sightLine.update(cell, this.getCellPosition(cell));
                }
              } else {
                const index = this.getGridIndex(state.occupant),
                  trace = this.counter.getTrace(toPlace),
                  pos = this.getCellPosition(cell),
                  points = trace.getAttribute('points').split(' ').filter(p => p != `${pos.x},${pos.y}`).join(' ');;

                let current = toPlace;

                trace.setAttributeNS(null, 'points', points);

                while (current.dataset.previous != `${index.x},${index.y}`) {
                  current = this.getCounterAtGridIndex(...current.dataset.previous.split(','));
                }

                current.dataset.previous = state.occupant.dataset.previous;
                state.occupant.remove();
              }
            }
            this.placing.push(toPlace);
          }
        } else if (!toPlace && state.occupant) {
          this.select(state.occupant);
        } else {
          console.log('removing cell contents');
          state.contents.forEach(el => el.remove());
        }
      });

      cell.addEventListener('dblclick', e => {
        const toPlace = this.placing.pop(),
          occupant = this.getCellOccupant(cell);

        if (toPlace && occupant && toPlace == occupant) {
          const { number, allegiance } = toPlace.dataset,
            selector = `[data-allegiance="${allegiance}"][data-number="${number}"]`;

          this.svg.querySelectorAll(selector).forEach(el => el.remove());
        }
      });

      // 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.
      cell.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 {
            cell.querySelector(`use[href="#hex"]`).classList.add('sight-line-target');
          }

          cell.dispatchEvent(new MouseEvent('pointerover'));
        }
      });

      cell.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 != cell) {
            this.sightLine.draw(sourceCell, cell);
          }
        }

        let occupant = this.getCellOccupant(cell);

        if (occupant) {
          const { number, allegiance } = occupant.dataset;
          const cp = this.svg.querySelector(`#clip-path-${allegiance}-${number}`);

          if (cp) {
            cp.style.display = 'none';
          }
        }
      });

      cell.addEventListener('pointerout', e => {
        let sl = this.svg.querySelector('.sight-line.active');

        if (sl && sl.classList.contains('active')) {
          this.sightLine.clear();
        }

        let occupant = this.getCellOccupant(cell);

        if (occupant) {
          let { number, allegiance } = occupant.dataset,
            cp = this.svg.querySelector(`#clip-path-${allegiance}-${number}`);

          if (cp) {
            cp.style.display = this.#firingArcVisibility[allegiance] ? 'none' : '';
          }
        }
      });
    });
  }

  setFiringArc(size) {
    const counter = this.getSelected(),
      isOnBoard = counter => counter && counter.parentElement.hasAttribute('data-x');

    if (isOnBoard(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');

    this.placing.push(counter);
  }
}