A bit more flexibility in boards drawing
[vchess.git] / client / src / components / Board.vue
1 <script>
2 import { getSquareId, getSquareFromId } from "@/utils/squareId";
3 import { ArrayFun } from "@/utils/array";
4 import { store } from "@/store";
5 export default {
6 name: "my-board",
7 // Last move cannot be guessed from here, and is required for highlights.
8 // vr: object to check moves, print board...
9 // userColor is left undefined for an external observer
10 props: [
11 "vr",
12 "lastMove",
13 "analyze",
14 "score",
15 "incheck",
16 "orientation",
17 "userColor",
18 "vname"
19 ],
20 data: function() {
21 return {
22 mobileBrowser: ("ontouchstart" in window),
23 possibleMoves: [], //filled after each valid click/dragstart
24 choices: [], //promotion pieces, or checkered captures... (as moves)
25 containerPos: null,
26 selectedPiece: null, //moving piece (or clicked piece)
27 start: null, //pixels coordinates + id of starting square (click or drag)
28 startArrow: null,
29 movingArrow: null,
30 arrows: [], //object of {start: x,y / end: x,y}
31 circles: {}, //object of squares' ID --> true (TODO: use a set?)
32 click: "",
33 clickTime: 0,
34 settings: store.state.settings
35 };
36 },
37 render(h) {
38 if (!this.vr) {
39 // Return empty div of class 'game' to avoid error when setting size
40 return h(
41 "div",
42 { "class": { game: true } }
43 );
44 }
45 const [sizeX, sizeY] = [V.size.x, V.size.y];
46 // Precompute hints squares to facilitate rendering
47 let hintSquares = ArrayFun.init(sizeX, sizeY, false);
48 this.possibleMoves.forEach(m => {
49 hintSquares[m.end.x][m.end.y] = true;
50 });
51 // Also precompute in-check squares
52 let incheckSq = ArrayFun.init(sizeX, sizeY, false);
53 this.incheck.forEach(sq => {
54 incheckSq[sq[0]][sq[1]] = true;
55 });
56
57 let lm = this.lastMove;
58 // Precompute lastMove highlighting squares
59 const lmHighlights = {};
60 if (!!lm) {
61 if (!Array.isArray(lm)) lm = [lm];
62 lm.forEach(m => {
63 if (!m.start.noHighlight && V.OnBoard(m.start.x, m.start.y))
64 lmHighlights[m.start.x + sizeX * m.start.y] = true;
65 if (!m.end.noHighlight && V.OnBoard(m.end.x, m.end.y))
66 lmHighlights[m.end.x + sizeX * m.end.y] = true;
67 if (!!m.start.toplay)
68 // For Dice variant (at least?)
69 lmHighlights[m.start.toplay[0] + sizeX * m.start.toplay[1]] = true;
70 });
71 }
72 const showLight = (
73 this.settings.highlight &&
74 ["all", "highlight"].includes(V.ShowMoves)
75 );
76 const showCheck = (
77 this.settings.highlight &&
78 ["all", "highlight", "byrow"].includes(V.ShowMoves)
79 );
80 const orientation = !V.CanFlip ? "w" : this.orientation;
81 // Ensure that squares colors do not change when board is flipped
82 const lightSquareMod = (sizeX + sizeY) % 2;
83 const showPiece = (x, y) => {
84 return (
85 this.vr.board[x][y] != V.EMPTY &&
86 (!this.vr.enlightened || this.analyze || this.score != "*" ||
87 (!!this.userColor && this.vr.enlightened[this.userColor][x][y]))
88 );
89 };
90 const inHighlight = (x, y) => {
91 return showLight && !!lmHighlights[x + sizeX * y];
92 };
93 const inShadow = (x, y) => {
94 return (
95 !this.analyze &&
96 this.score == "*" &&
97 this.vr.enlightened &&
98 (!this.userColor || !this.vr.enlightened[this.userColor][x][y])
99 );
100 };
101 // Create board element (+ reserves if needed by variant)
102 let elementArray = [];
103 const gameDiv = h(
104 "div",
105 {
106 attrs: { id: "gamePosition" },
107 "class": {
108 game: true,
109 clearer: true
110 }
111 },
112 [...Array(sizeX).keys()].map(i => {
113 const ci = orientation == "w" ? i : sizeX - i - 1;
114 return h(
115 "div",
116 {
117 "class": {
118 row: true
119 },
120 style: { opacity: this.choices.length > 0 ? "0.5" : "1" }
121 },
122 [...Array(sizeY).keys()].map(j => {
123 const cj = orientation == "w" ? j : sizeY - j - 1;
124 const squareId = "sq-" + ci + "-" + cj;
125 let elems = [];
126 if (showPiece(ci, cj)) {
127 let pieceSpecs = {
128 "class": {
129 piece: true,
130 ghost:
131 !!this.selectedPiece &&
132 this.selectedPiece.parentNode.id == squareId
133 },
134 attrs: {
135 src:
136 "/images/pieces/" +
137 this.vr.getPpath(
138 this.vr.board[ci][cj],
139 // Extra args useful for some variants:
140 this.userColor,
141 this.score,
142 this.orientation) +
143 V.IMAGE_EXTENSION
144 }
145 };
146 if (this.arrows.length == 0)
147 pieceSpecs["style"] = { position: "absolute" };
148 elems.push(h("img", pieceSpecs));
149 }
150 if (this.settings.hints && hintSquares[ci][cj]) {
151 elems.push(
152 h("img", {
153 "class": {
154 "mark-square": true
155 },
156 attrs: {
157 src: "/images/mark.svg"
158 }
159 })
160 );
161 }
162 if (!!this.circles[squareId]) {
163 elems.push(
164 h("img", {
165 "class": {
166 "circle-square": true
167 },
168 attrs: {
169 src: "/images/circle.svg"
170 }
171 })
172 );
173 }
174 const oddity = (ci + cj) % 2;
175 const lightSquare = (
176 (!V.DarkBottomRight && oddity == lightSquareMod) ||
177 (V.DarkBottomRight && oddity != lightSquareMod)
178 );
179 return h(
180 "div",
181 {
182 "class": {
183 board: true,
184 ["board" + sizeY]: true,
185 "light-square":
186 !V.Notoodark && lightSquare && !V.Monochrome,
187 "dark-square":
188 !V.Notoodark && (!lightSquare || !!V.Monochrome),
189 "middle-square": V.Notoodark,
190 [this.settings.bcolor]: true,
191 "in-shadow": inShadow(ci, cj),
192 "highlight": inHighlight(ci, cj),
193 "incheck-light":
194 showCheck && lightSquare && incheckSq[ci][cj],
195 "incheck-dark":
196 showCheck && !lightSquare && incheckSq[ci][cj],
197 "hover-highlight": this.vr.hoverHighlight(ci, cj)
198 },
199 attrs: {
200 id: getSquareId({ x: ci, y: cj })
201 }
202 },
203 elems
204 );
205 })
206 );
207 })
208 );
209 if (!!this.vr.reserve) {
210 const playingColor = this.userColor || "w"; //default for an observer
211 const shiftIdx = playingColor == "w" ? 0 : 1;
212 // Some variants have more than sizeY reserve pieces (Clorange: 10)
213 const reserveSquareNb = Math.max(sizeY, V.RESERVE_PIECES.length);
214 let myReservePiecesArray = [];
215 if (!!this.vr.reserve[playingColor]) {
216 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
217 const qty = this.vr.reserve[playingColor][V.RESERVE_PIECES[i]];
218 myReservePiecesArray.push(
219 h(
220 "div",
221 {
222 "class": { board: true, ["board" + reserveSquareNb]: true },
223 attrs: { id: getSquareId({ x: sizeX + shiftIdx, y: i }) },
224 style: { opacity: qty > 0 ? 1 : 0.35 }
225 },
226 [
227 h("img", {
228 // NOTE: class "reserve" not used currently
229 "class": { piece: true, reserve: true },
230 attrs: {
231 src:
232 "/images/pieces/" +
233 this.vr.getReservePpath(i, playingColor, orientation) +
234 ".svg"
235 }
236 }),
237 h(
238 "sup",
239 {
240 "class": { "reserve-count": true },
241 style: { top: "calc(100% + 5px)" }
242 },
243 [ qty ]
244 )
245 ]
246 )
247 );
248 }
249 }
250 let oppReservePiecesArray = [];
251 const oppCol = V.GetOppCol(playingColor);
252 if (!!this.vr.reserve[oppCol]) {
253 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
254 const qty = this.vr.reserve[oppCol][V.RESERVE_PIECES[i]];
255 oppReservePiecesArray.push(
256 h(
257 "div",
258 {
259 "class": { board: true, ["board" + reserveSquareNb]: true },
260 attrs: { id: getSquareId({ x: sizeX + (1 - shiftIdx), y: i }) },
261 style: { opacity: qty > 0 ? 1 : 0.35 }
262 },
263 [
264 h("img", {
265 "class": { piece: true, reserve: true },
266 attrs: {
267 src:
268 "/images/pieces/" +
269 this.vr.getReservePpath(i, oppCol, orientation) +
270 ".svg"
271 }
272 }),
273 h(
274 "sup",
275 {
276 "class": { "reserve-count": true },
277 style: { top: "calc(100% + 5px)" }
278 },
279 [ qty ]
280 )
281 ]
282 )
283 );
284 }
285 }
286 const myReserveTop = (
287 (playingColor == 'w' && orientation == 'b') ||
288 (playingColor == 'b' && orientation == 'w')
289 );
290 const hasReserveTop = (
291 (myReserveTop && !!this.vr.reserve[playingColor]) ||
292 (!myReserveTop && !!this.vr.reserve[oppCol])
293 );
294 // "var" because must be reachable from outside this block
295 var hasReserveBottom = (
296 (myReserveTop && !!this.vr.reserve[oppCol]) ||
297 (!myReserveTop && !!this.vr.reserve[playingColor])
298 );
299 // Center reserves, assuming same number of pieces for each side:
300 const nbReservePieces = myReservePiecesArray.length;
301 const marginLeft =
302 ((100 - nbReservePieces * (100 / reserveSquareNb)) / 2) + "%";
303 if (hasReserveTop) {
304 var reserveTop =
305 h(
306 "div",
307 {
308 "class": {
309 game: true,
310 "reserve-div": true
311 },
312 style: {
313 "margin-left": marginLeft
314 }
315 },
316 [
317 h(
318 "div",
319 {
320 "class": {
321 row: true,
322 "reserve-row": true
323 }
324 },
325 myReserveTop ? myReservePiecesArray : oppReservePiecesArray
326 )
327 ]
328 );
329 }
330 if (hasReserveBottom) {
331 var reserveBottom =
332 h(
333 "div",
334 {
335 "class": {
336 game: true,
337 "reserve-div": true
338 },
339 style: {
340 "margin-left": marginLeft
341 }
342 },
343 [
344 h(
345 "div",
346 {
347 "class": {
348 row: true,
349 "reserve-row": true
350 }
351 },
352 myReserveTop ? oppReservePiecesArray : myReservePiecesArray
353 )
354 ]
355 );
356 }
357 if (hasReserveTop) elementArray.push(reserveTop);
358 }
359 elementArray.push(gameDiv);
360 if (!!this.vr.reserve && hasReserveBottom)
361 elementArray.push(reserveBottom);
362 const boardElt = document.getElementById("gamePosition");
363 // boardElt might be undefine (at first drawing)
364 if (this.choices.length > 0 && !!boardElt) {
365 const squareWidth = boardElt.offsetWidth / sizeY;
366 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
367 const maxNbeltsPerRow = Math.min(this.choices.length, sizeY);
368 let topOffset = offset[0] + (sizeY / 2) * squareWidth - squareWidth / 2;
369 let choicesHeight = squareWidth;
370 if (this.choices.length >= sizeY) {
371 // A second row is required (Eightpieces variant)
372 topOffset -= squareWidth / 2;
373 choicesHeight *= 2;
374 }
375 const choices = h(
376 "div",
377 {
378 attrs: { id: "choices" },
379 "class": { row: true },
380 style: {
381 top: topOffset + "px",
382 left:
383 offset[1] +
384 (squareWidth * Math.max(sizeY - this.choices.length, 0)) / 2 +
385 "px",
386 width: (maxNbeltsPerRow * squareWidth) + "px",
387 height: choicesHeight + "px"
388 }
389 },
390 [ h(
391 "div",
392 {
393 "class": { "full-width": true }
394 },
395 this.choices.map(m => {
396 // A "choice" is a move
397 const applyMove = (e) => {
398 e.stopPropagation();
399 // Force a delay between move is shown and clicked
400 // (otherwise a "double-click" bug might occur)
401 if (Date.now() - this.clickTime < 200) return;
402 this.choices = [];
403 this.play(m);
404 };
405 const onClick =
406 this.mobileBrowser
407 ? { touchend: applyMove }
408 : { mouseup: applyMove };
409 return h(
410 "div",
411 {
412 "class": {
413 board: true,
414 ["board" + sizeY]: true
415 },
416 style: {
417 width: (100 / maxNbeltsPerRow) + "%",
418 "padding-bottom": (100 / maxNbeltsPerRow) + "%"
419 }
420 },
421 [
422 h("img", {
423 attrs: {
424 src:
425 "/images/pieces/" +
426 // orientation: extra arg useful for some variants:
427 this.vr.getPPpath(m, this.orientation) +
428 V.IMAGE_EXTENSION
429 },
430 "class": { "choice-piece": true },
431 on: onClick
432 })
433 ]
434 );
435 })
436 ) ]
437 );
438 elementArray.unshift(choices);
439 }
440 let onEvents = {};
441 // NOTE: click = mousedown + mouseup
442 if (this.mobileBrowser) {
443 onEvents = {
444 on: {
445 touchstart: this.mousedown,
446 touchmove: this.mousemove,
447 touchend: this.mouseup
448 }
449 };
450 }
451 else {
452 onEvents = {
453 on: {
454 mousedown: this.mousedown,
455 mousemove: this.mousemove,
456 mouseup: this.mouseup,
457 contextmenu: this.blockContextMenu
458 }
459 };
460 }
461 return (
462 h(
463 "div",
464 Object.assign({ attrs: { id: "rootBoardElement" } }, onEvents),
465 elementArray
466 )
467 );
468 },
469 updated: function() {
470 this.re_setDrawings();
471 },
472 methods: {
473 blockContextMenu: function(e) {
474 e.preventDefault();
475 e.stopPropagation();
476 return false;
477 },
478 cancelResetArrows: function() {
479 this.startArrow = null;
480 this.arrows = [];
481 this.circles = {};
482 const curCanvas = document.getElementById("arrowCanvas");
483 if (!!curCanvas) curCanvas.parentNode.removeChild(curCanvas);
484 },
485 coordsToXY: function(coords, top, left, squareWidth) {
486 return {
487 // [1] for x and [0] for y because conventions in rules are inversed.
488 x: (
489 left + window.scrollX +
490 (
491 squareWidth *
492 (this.orientation == 'w' ? coords[1] : (V.size.y - coords[1]))
493 )
494 ),
495 y: (
496 top + window.scrollY +
497 (
498 squareWidth *
499 (this.orientation == 'w' ? coords[0] : (V.size.x - coords[0]))
500 )
501 )
502 };
503 },
504 computeEndArrow: function(start, end, top, left, squareWidth) {
505 const endCoords = this.coordsToXY(end, top, left, squareWidth);
506 const delta = [endCoords.x - start.x, endCoords.y - start.y];
507 const dist = Math.sqrt(delta[0] * delta[0] + delta[1] * delta[1]);
508 // Simple heuristic for now, just remove 1/3 square.
509 // TODO: should depend on the orientation.
510 const fracSqWidth = squareWidth / 3;
511 return {
512 x: endCoords.x - delta[0] * fracSqWidth / dist,
513 y: endCoords.y - delta[1] * fracSqWidth / dist
514 };
515 },
516 drawCurrentArrow: function() {
517 const boardElt = document.getElementById("gamePosition");
518 const squareWidth = boardElt.offsetWidth / V.size.y;
519 const bPos = boardElt.getBoundingClientRect();
520 const aStart =
521 this.coordsToXY(
522 [this.startArrow[0] + 0.5, this.startArrow[1] + 0.5],
523 bPos.top, bPos.left, squareWidth);
524 const aEnd =
525 this.computeEndArrow(
526 aStart, [this.movingArrow[0] + 0.5, this.movingArrow[1] + 0.5],
527 bPos.top, bPos.left, squareWidth);
528 let currentArrow = document.getElementById("currentArrow");
529 const d =
530 "M" + aStart.x + "," + aStart.y + " " + "L" + aEnd.x + "," + aEnd.y;
531 const arrowWidth = squareWidth / 4;
532 if (!!currentArrow) currentArrow.setAttribute("d", d);
533 else {
534 let domArrow =
535 document.createElementNS("http://www.w3.org/2000/svg", "path");
536 domArrow.classList.add("svg-arrow");
537 domArrow.id = "currentArrow";
538 domArrow.setAttribute("d", d);
539 domArrow.style = "stroke-width:" + arrowWidth + "px";
540 document.getElementById("arrowCanvas")
541 .insertAdjacentElement("beforeend", domArrow);
542 }
543 },
544 addArrow: function(arrow) {
545 this.arrows.push(arrow);
546 // Also add to DOM:
547 const boardElt = document.getElementById("gamePosition");
548 const squareWidth = boardElt.offsetWidth / V.size.y;
549 const bPos = boardElt.getBoundingClientRect();
550 const newArrow =
551 this.getSvgArrow(arrow, bPos.top, bPos.left, squareWidth);
552 document.getElementById("arrowCanvas")
553 .insertAdjacentElement("beforeend", newArrow);
554 },
555 getSvgArrow: function(arrow, top, left, squareWidth) {
556 const aStart =
557 this.coordsToXY(
558 [arrow.start[0] + 0.5, arrow.start[1] + 0.5],
559 top, left, squareWidth);
560 const aEnd =
561 this.computeEndArrow(
562 aStart, [arrow.end[0] + 0.5, arrow.end[1] + 0.5],
563 top, left, squareWidth);
564 const arrowWidth = squareWidth / 4;
565 let path =
566 document.createElementNS("http://www.w3.org/2000/svg", "path");
567 path.classList.add("svg-arrow");
568 path.setAttribute(
569 "d",
570 "M" + aStart.x + "," + aStart.y + " " + "L" + aEnd.x + "," + aEnd.y
571 );
572 path.style = "stroke-width:" + arrowWidth + "px";
573 return path;
574 },
575 re_setDrawings: function() {
576 // Remove current canvas, if any
577 const curCanvas = document.getElementById("arrowCanvas");
578 if (!!curCanvas) curCanvas.parentNode.removeChild(curCanvas);
579 // Add some drawing on board (for some variants + arrows and circles)
580 const boardElt = document.getElementById("gamePosition");
581 const squareWidth = boardElt.offsetWidth / V.size.y;
582 const bPos = boardElt.getBoundingClientRect();
583 let svgArrows = [];
584 this.arrows.forEach(a => {
585 svgArrows.push(this.getSvgArrow(a, bPos.top, bPos.left, squareWidth));
586 });
587 let vLines = [];
588 if (!!V.Lines) {
589 V.Lines.forEach(line => {
590 const lStart =
591 this.coordsToXY(line[0], bPos.top, bPos.left, squareWidth);
592 const lEnd =
593 this.coordsToXY(line[1], bPos.top, bPos.left, squareWidth);
594 let path =
595 document.createElementNS("http://www.w3.org/2000/svg", "path");
596 if (line[0][0] == line[1][0] || line[0][1] == line[1][1])
597 path.classList.add("svg-line");
598 else
599 // "Diagonals" are drawn with a lighter color (TODO: generalize)
600 path.classList.add("svg-diag");
601 path.setAttribute(
602 "d",
603 "M" + lStart.x + "," + lStart.y + " " +
604 "L" + lEnd.x + "," + lEnd.y
605 );
606 vLines.push(path);
607 });
608 }
609 let arrowCanvas =
610 document.createElementNS("http://www.w3.org/2000/svg", "svg");
611 arrowCanvas.id = "arrowCanvas";
612 arrowCanvas.setAttribute("stroke", "none");
613 let defs =
614 document.createElementNS("http://www.w3.org/2000/svg", "defs");
615 const arrowWidth = squareWidth / 4;
616 let marker =
617 document.createElementNS("http://www.w3.org/2000/svg", "marker");
618 marker.id = "arrow";
619 marker.setAttribute("markerWidth", (2 * arrowWidth) + "px");
620 marker.setAttribute("markerHeight", (3 * arrowWidth) + "px");
621 marker.setAttribute("markerUnits", "userSpaceOnUse");
622 marker.setAttribute("refX", "0");
623 marker.setAttribute("refY", (1.5 * arrowWidth) + "px");
624 marker.setAttribute("orient", "auto");
625 let head =
626 document.createElementNS("http://www.w3.org/2000/svg", "path");
627 head.classList.add("arrow-head");
628 head.setAttribute(
629 "d",
630 "M0,0 L0," + (3 * arrowWidth) + " L" +
631 (2 * arrowWidth) + "," + (1.5 * arrowWidth) + " z"
632 );
633 marker.appendChild(head);
634 defs.appendChild(marker);
635 arrowCanvas.appendChild(defs);
636 svgArrows.concat(vLines).forEach(av => arrowCanvas.appendChild(av));
637 document.getElementById("rootBoardElement").appendChild(arrowCanvas);
638 },
639 mousedown: function(e) {
640 e.preventDefault();
641 if (!this.mobileBrowser && e.which != 3)
642 // Cancel current drawing and circles, if any
643 this.cancelResetArrows();
644 if (this.mobileBrowser || e.which == 1) {
645 // Mouse left button
646 if (!this.start) {
647 this.containerPos =
648 document.getElementById("boardContainer").getBoundingClientRect();
649 // NOTE: classList[0] is enough: 'piece' is the first assigned class
650 const withPiece = (e.target.classList[0] == "piece");
651 // Emit the click event which could be used by some variants
652 this.$emit(
653 "click-square",
654 getSquareFromId(withPiece ? e.target.parentNode.id : e.target.id)
655 );
656 // Start square must contain a piece.
657 if (!withPiece) return;
658 let parent = e.target.parentNode; //surrounding square
659 // Show possible moves if current player allowed to play
660 const startSquare = getSquareFromId(parent.id);
661 this.possibleMoves = [];
662 const color = this.analyze ? this.vr.turn : this.userColor;
663 if (this.vr.canIplay(color, startSquare))
664 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
665 else return;
666 // For potential drag'n drop, remember start coordinates
667 // (to center the piece on mouse cursor)
668 const rect = parent.getBoundingClientRect();
669 this.start = {
670 x: rect.x + rect.width / 2,
671 y: rect.y + rect.width / 2,
672 id: parent.id
673 };
674 // Add the moving piece to the board, just after current image
675 this.selectedPiece = e.target.cloneNode();
676 Object.assign(
677 this.selectedPiece.style,
678 {
679 position: "absolute",
680 top: 0,
681 display: "inline-block",
682 zIndex: 3000
683 }
684 );
685 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
686 } else {
687 this.processMoveAttempt(e);
688 }
689 } else if (e.which == 3) {
690 // Mouse right button
691 this.containerPos =
692 document.getElementById("gamePosition").getBoundingClientRect();
693 let elem = e.target;
694 // Next loop because of potential marks
695 while (elem.tagName == "IMG") elem = elem.parentNode;
696 this.startArrow = getSquareFromId(elem.id);
697 }
698 },
699 mousemove: function(e) {
700 if (!this.selectedPiece && !this.startArrow) return;
701 // Cancel if off boardContainer
702 const [offsetX, offsetY] =
703 this.mobileBrowser
704 ? [e.changedTouches[0].clientX, e.changedTouches[0].clientY]
705 : [e.clientX, e.clientY];
706 if (
707 offsetX < this.containerPos.left ||
708 offsetX > this.containerPos.right ||
709 offsetY < this.containerPos.top ||
710 offsetY > this.containerPos.bottom
711 ) {
712 if (!!this.selectedPiece) {
713 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
714 delete this.selectedPiece;
715 this.selectedPiece = null;
716 this.start = null;
717 this.possibleMoves = []; //in case of
718 this.click = "";
719 let selected = document.querySelector(".ghost");
720 if (!!selected) selected.classList.remove("ghost");
721 }
722 else {
723 this.startArrow = null;
724 this.movingArrow = null;
725 const currentArrow = document.getElementById("currentArrow");
726 if (!!currentArrow)
727 currentArrow.parentNode.removeChild(currentArrow);
728 }
729 return;
730 }
731 e.preventDefault();
732 if (!!this.selectedPiece) {
733 // There is an active element: move it around
734 Object.assign(
735 this.selectedPiece.style,
736 {
737 left: offsetX - this.start.x + "px",
738 top: offsetY - this.start.y + "px"
739 }
740 );
741 }
742 else {
743 let elem = e.target;
744 // Next loop because of potential marks
745 while (elem.tagName == "IMG") elem = elem.parentNode;
746 // To center the arrow in square:
747 const movingCoords = getSquareFromId(elem.id);
748 if (
749 movingCoords[0] != this.startArrow[0] ||
750 movingCoords[1] != this.startArrow[1]
751 ) {
752 this.movingArrow = movingCoords;
753 this.drawCurrentArrow();
754 }
755 }
756 },
757 mouseup: function(e) {
758 e.preventDefault();
759 if (this.mobileBrowser || e.which == 1) {
760 if (!this.selectedPiece) return;
761 // Drag'n drop. Selected piece is no longer needed:
762 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
763 delete this.selectedPiece;
764 this.selectedPiece = null;
765 this.processMoveAttempt(e);
766 } else if (e.which == 3) {
767 if (!this.startArrow) return;
768 // Mouse right button
769 this.movingArrow = null;
770 this.processArrowAttempt(e);
771 }
772 },
773 // Called by BaseGame after partially undoing multi-moves:
774 resetCurrentAttempt: function() {
775 this.possibleMoves = [];
776 this.start = null;
777 this.click = "";
778 this.selectedPiece = null;
779 },
780 processMoveAttempt: function(e) {
781 // Obtain the move from start and end squares
782 const [offsetX, offsetY] =
783 this.mobileBrowser
784 ? [e.changedTouches[0].clientX, e.changedTouches[0].clientY]
785 : [e.clientX, e.clientY];
786 let landing = document.elementFromPoint(offsetX, offsetY);
787 // Next condition: classList.contains(piece) fails because of marks
788 while (landing.tagName == "IMG") landing = landing.parentNode;
789 if (this.start.id == landing.id) {
790 if (this.click == landing.id) {
791 // Second click on same square: cancel current move
792 this.possibleMoves = [];
793 this.start = null;
794 this.click = "";
795 } else this.click = landing.id;
796 return;
797 }
798 this.start = null;
799 // OK: process move attempt, landing is a square node
800 let endSquare = getSquareFromId(landing.id);
801 let moves = this.findMatchingMoves(endSquare);
802 this.possibleMoves = [];
803 if (moves.length > 1) {
804 this.clickTime = Date.now();
805 this.choices = moves;
806 } else if (moves.length == 1) this.play(moves[0]);
807 // else: forbidden move attempt
808 },
809 processArrowAttempt: function(e) {
810 // Obtain the arrow from start and end squares
811 const [offsetX, offsetY] = [e.clientX, e.clientY];
812 let landing = document.elementFromPoint(offsetX, offsetY);
813 // Next condition: classList.contains(piece) fails because of marks
814 while (landing.tagName == "IMG") landing = landing.parentNode;
815 const landingCoords = getSquareFromId(landing.id);
816 if (
817 this.startArrow[0] == landingCoords[0] &&
818 this.startArrow[1] == landingCoords[1]
819 ) {
820 // Draw (or erase) a circle
821 this.$set(this.circles, landing.id, !this.circles[landing.id]);
822 }
823 else {
824 // OK: add arrow, landing is a new square
825 const currentArrow = document.getElementById("currentArrow");
826 currentArrow.parentNode.removeChild(currentArrow);
827 this.addArrow({
828 start: this.startArrow,
829 end: landingCoords
830 });
831 }
832 this.startArrow = null;
833 },
834 findMatchingMoves: function(endSquare) {
835 // Run through moves list and return the matching set (if promotions...)
836 return (
837 this.possibleMoves.filter(m => {
838 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
839 })
840 );
841 },
842 play: function(move) {
843 this.$emit("play-move", move);
844 }
845 }
846 };
847 </script>
848
849 <style lang="sass">
850 // SVG dynamically added, so not scoped
851 #arrowCanvas
852 pointer-events: none
853 position: absolute
854 top: 0
855 left: 0
856 width: 100%
857 height: 100%
858
859 .svg-arrow
860 opacity: 0.65
861 stroke: #5f0e78
862 fill: none
863 marker-end: url(#arrow)
864
865 .svg-line
866 stroke: black
867
868 .svg-diag
869 stroke: grey
870
871 .arrow-head
872 fill: #5f0e78
873 </style>
874
875 <style lang="sass" scoped>
876 @import "@/styles/_board_squares_img.sass";
877
878 //.game.reserve-div
879 // TODO: would be cleaner to restrict width so that it doesn't overflow
880 // Commented out because pieces would disappear over the board otherwise:
881 //overflow: hidden
882 .reserve-count
883 width: 100%
884 text-align: center
885 display: inline-block
886 position: absolute
887 .reserve-row
888 margin-bottom: 15px
889
890 .full-width
891 width: 100%
892
893 .game
894 user-select: none
895 width: 100%
896 margin: 0
897 .board
898 cursor: pointer
899
900 #choices
901 user-select: none
902 margin: 0
903 position: absolute
904 z-index: 300
905 overflow-y: inherit
906 background-color: rgba(0,0,0,0)
907 img
908 cursor: pointer
909 background-color: #e6ee9c
910 &:hover
911 background-color: skyblue
912 &.choice-piece
913 width: 100%
914 height: auto
915 display: block
916
917 img.ghost
918 // NOTE: no need to set z-index here, since opacity is low
919 position: absolute
920 opacity: 0.5
921 top: 0
922
923 .incheck-light
924 background-color: rgba(204, 51, 0, 0.7) !important
925 .incheck-dark
926 background-color: rgba(204, 51, 0, 0.9) !important
927
928 // TODO: no predefined highlight colors, but layers. How?
929
930 .hover-highlight:hover
931 // TODO: color dependant on board theme, or inner border...
932 background-color: #C571E6 !important
933
934 .highlight
935 &.light-square
936 &.lichess
937 background-color: #cdd26a
938 &.chesscom
939 background-color: #f7f783
940 &.chesstempo
941 background-color: #9f9fff
942 &.orangecc
943 background-color: #fef273
944 &.dark-square
945 &.lichess
946 background-color: #aaa23a
947 &.chesscom
948 background-color: #bacb44
949 &.chesstempo
950 background-color: #557fff
951 &.orangecc
952 background-color: #e8c525
953 &.middle-square
954 &.lichess
955 background-color: #BCBA52
956 &.chesscom
957 background-color: #D9E164
958 &.chesstempo
959 background-color: #7A8FFF
960 &.orangecc
961 background-color: #F3DC4C
962 </style>