2 import { getSquareId, getSquareFromId } from "@/utils/squareId";
3 import { ArrayFun } from "@/utils/array";
4 import { store } from "@/store";
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
22 mobileBrowser: ("ontouchstart" in window),
23 possibleMoves: [], //filled after each valid click/dragstart
24 choices: [], //promotion pieces, or checkered captures... (as moves)
26 selectedPiece: null, //moving piece (or clicked piece)
27 start: null, //pixels coordinates + id of starting square (click or drag)
30 arrows: [], //object of {start: x,y / end: x,y}
31 circles: {}, //object of squares' ID --> true (TODO: use a set?)
34 settings: store.state.settings
39 // Return empty div of class 'game' to avoid error when setting size
42 { "class": { game: true } }
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;
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;
57 let lm = this.lastMove;
58 // Precompute lastMove highlighting squares
59 const lmHighlights = {};
61 if (!Array.isArray(lm)) lm = [lm];
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;
68 // For Dice variant (at least?)
69 lmHighlights[m.start.toplay[0] + sizeX * m.start.toplay[1]] = true;
73 this.settings.highlight &&
74 ["all", "highlight"].includes(V.ShowMoves)
77 this.settings.highlight &&
78 ["all", "highlight", "byrow"].includes(V.ShowMoves)
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) => {
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]))
90 const inHighlight = (x, y) => {
91 return showLight && !!lmHighlights[x + sizeX * y];
93 const inShadow = (x, y) => {
97 this.vr.enlightened &&
98 (!this.userColor || !this.vr.enlightened[this.userColor][x][y])
101 // Create board element (+ reserves if needed by variant)
102 let elementArray = [];
106 attrs: { id: "gamePosition" },
112 [...Array(sizeX).keys()].map(i => {
113 const ci = orientation == "w" ? i : sizeX - i - 1;
120 style: { opacity: this.choices.length > 0 ? "0.5" : "1" }
122 [...Array(sizeY).keys()].map(j => {
123 const cj = orientation == "w" ? j : sizeY - j - 1;
124 const squareId = "sq-" + ci + "-" + cj;
126 if (showPiece(ci, cj)) {
131 !!this.selectedPiece &&
132 this.selectedPiece.parentNode.id == squareId
138 this.vr.board[ci][cj],
139 // Extra args useful for some variants:
146 if (this.arrows.length == 0)
147 pieceSpecs["style"] = { position: "absolute" };
148 elems.push(h("img", pieceSpecs));
150 if (this.settings.hints && hintSquares[ci][cj]) {
157 src: "/images/mark.svg"
162 if (!!this.circles[squareId]) {
166 "circle-square": true
169 src: "/images/circle.svg"
174 const lightSquare = (ci + cj) % 2 == lightSquareMod;
180 ["board" + sizeY]: true,
182 !V.Notoodark && lightSquare && !V.Monochrome,
184 !V.Notoodark && (!lightSquare || !!V.Monochrome),
185 "middle-square": V.Notoodark,
186 [this.settings.bcolor]: true,
187 "in-shadow": inShadow(ci, cj),
188 "highlight-light": inHighlight(ci, cj) && lightSquare,
190 inHighlight(ci, cj) && (V.Monochrome || !lightSquare),
192 showCheck && lightSquare && incheckSq[ci][cj],
194 showCheck && !lightSquare && incheckSq[ci][cj],
195 "hover-highlight": this.vr.hoverHighlight(ci, cj)
198 id: getSquareId({ x: ci, y: cj })
207 if (!!this.vr.reserve) {
208 const playingColor = this.userColor || "w"; //default for an observer
209 const shiftIdx = playingColor == "w" ? 0 : 1;
210 // Some variants have more than sizeY reserve pieces (Clorange: 10)
211 const reserveSquareNb = Math.max(sizeY, V.RESERVE_PIECES.length);
212 let myReservePiecesArray = [];
213 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
214 const qty = this.vr.reserve[playingColor][V.RESERVE_PIECES[i]];
215 myReservePiecesArray.push(
219 "class": { board: true, ["board" + reserveSquareNb]: true },
220 attrs: { id: getSquareId({ x: sizeX + shiftIdx, y: i }) },
221 style: { opacity: qty > 0 ? 1 : 0.35 }
225 // NOTE: class "reserve" not used currently
226 "class": { piece: true, reserve: true },
230 this.vr.getReservePpath(i, playingColor, orientation) +
237 "class": { "reserve-count": true },
238 style: { top: "calc(100% + 5px)" }
246 let oppReservePiecesArray = [];
247 const oppCol = V.GetOppCol(playingColor);
248 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
249 const qty = this.vr.reserve[oppCol][V.RESERVE_PIECES[i]];
250 oppReservePiecesArray.push(
254 "class": { board: true, ["board" + reserveSquareNb]: true },
255 attrs: { id: getSquareId({ x: sizeX + (1 - shiftIdx), y: i }) },
256 style: { opacity: qty > 0 ? 1 : 0.35 }
260 "class": { piece: true, reserve: true },
264 this.vr.getReservePpath(i, oppCol, orientation) +
271 "class": { "reserve-count": true },
272 style: { top: "calc(100% + 5px)" }
280 const myReserveTop = (
281 (playingColor == 'w' && orientation == 'b') ||
282 (playingColor == 'b' && orientation == 'w')
284 // Center reserves, assuming same number of pieces for each side:
285 const nbReservePieces = myReservePiecesArray.length;
287 ((100 - nbReservePieces * (100 / reserveSquareNb)) / 2) + "%";
297 "margin-left": marginLeft
309 myReserveTop ? myReservePiecesArray : oppReservePiecesArray
322 "margin-left": marginLeft
334 myReserveTop ? oppReservePiecesArray : myReservePiecesArray
338 elementArray.push(reserveTop);
340 elementArray.push(gameDiv);
341 if (!!this.vr.reserve) elementArray.push(reserveBottom);
342 const boardElt = document.getElementById("gamePosition");
343 // boardElt might be undefine (at first drawing)
344 if (this.choices.length > 0 && !!boardElt) {
345 const squareWidth = boardElt.offsetWidth / sizeY;
346 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
347 const maxNbeltsPerRow = Math.min(this.choices.length, sizeY);
348 let topOffset = offset[0] + (sizeY / 2) * squareWidth - squareWidth / 2;
349 let choicesHeight = squareWidth;
350 if (this.choices.length >= sizeY) {
351 // A second row is required (Eightpieces variant)
352 topOffset -= squareWidth / 2;
358 attrs: { id: "choices" },
359 "class": { row: true },
361 top: topOffset + "px",
364 (squareWidth * Math.max(sizeY - this.choices.length, 0)) / 2 +
366 width: (maxNbeltsPerRow * squareWidth) + "px",
367 height: choicesHeight + "px"
373 "class": { "full-width": true }
375 this.choices.map(m => {
376 // A "choice" is a move
377 const applyMove = (e) => {
379 // Force a delay between move is shown and clicked
380 // (otherwise a "double-click" bug might occur)
381 if (Date.now() - this.clickTime < 200) return;
387 ? { touchend: applyMove }
388 : { mouseup: applyMove };
394 ["board" + sizeY]: true
397 width: (100 / maxNbeltsPerRow) + "%",
398 "padding-bottom": (100 / maxNbeltsPerRow) + "%"
406 // orientation: extra arg useful for some variants:
407 this.vr.getPPpath(m, this.orientation) +
410 "class": { "choice-piece": true },
418 elementArray.unshift(choices);
421 // NOTE: click = mousedown + mouseup
422 if (this.mobileBrowser) {
425 touchstart: this.mousedown,
426 touchmove: this.mousemove,
427 touchend: this.mouseup
433 mousedown: this.mousedown,
434 mousemove: this.mousemove,
435 mouseup: this.mouseup,
436 contextmenu: this.blockContextMenu
443 Object.assign({ attrs: { id: "rootBoardElement" } }, onEvents),
448 updated: function() {
449 this.re_setDrawings();
452 blockContextMenu: function(e) {
457 cancelResetArrows: function() {
458 this.startArrow = null;
461 const curCanvas = document.getElementById("arrowCanvas");
462 if (!!curCanvas) curCanvas.parentNode.removeChild(curCanvas);
464 coordsToXY: function(coords, top, left, squareWidth) {
466 // [1] for x and [0] for y because conventions in rules are inversed.
468 left + window.scrollX +
471 (this.orientation == 'w' ? coords[1] : (V.size.y - coords[1]))
475 top + window.scrollY +
478 (this.orientation == 'w' ? coords[0] : (V.size.x - coords[0]))
483 computeEndArrow: function(start, end, top, left, squareWidth) {
484 const endCoords = this.coordsToXY(end, top, left, squareWidth);
485 const delta = [endCoords.x - start.x, endCoords.y - start.y];
486 const dist = Math.sqrt(delta[0] * delta[0] + delta[1] * delta[1]);
487 // Simple heuristic for now, just remove 1/3 square.
488 // TODO: should depend on the orientation.
489 const fracSqWidth = squareWidth / 3;
491 x: endCoords.x - delta[0] * fracSqWidth / dist,
492 y: endCoords.y - delta[1] * fracSqWidth / dist
495 drawCurrentArrow: function() {
496 const boardElt = document.getElementById("gamePosition");
497 const squareWidth = boardElt.offsetWidth / V.size.y;
498 const bPos = boardElt.getBoundingClientRect();
501 [this.startArrow[0] + 0.5, this.startArrow[1] + 0.5],
502 bPos.top, bPos.left, squareWidth);
504 this.computeEndArrow(
505 aStart, [this.movingArrow[0] + 0.5, this.movingArrow[1] + 0.5],
506 bPos.top, bPos.left, squareWidth);
507 let currentArrow = document.getElementById("currentArrow");
509 "M" + aStart.x + "," + aStart.y + " " + "L" + aEnd.x + "," + aEnd.y;
510 const arrowWidth = squareWidth / 4;
511 if (!!currentArrow) currentArrow.setAttribute("d", d);
514 document.createElementNS("http://www.w3.org/2000/svg", "path");
515 domArrow.classList.add("svg-arrow");
516 domArrow.id = "currentArrow";
517 domArrow.setAttribute("d", d);
518 domArrow.style = "stroke-width:" + arrowWidth + "px";
519 document.getElementById("arrowCanvas")
520 .insertAdjacentElement("beforeend", domArrow);
523 addArrow: function(arrow) {
524 this.arrows.push(arrow);
526 const boardElt = document.getElementById("gamePosition");
527 const squareWidth = boardElt.offsetWidth / V.size.y;
528 const bPos = boardElt.getBoundingClientRect();
530 this.getSvgArrow(arrow, bPos.top, bPos.left, squareWidth);
531 document.getElementById("arrowCanvas")
532 .insertAdjacentElement("beforeend", newArrow);
534 getSvgArrow: function(arrow, top, left, squareWidth) {
537 [arrow.start[0] + 0.5, arrow.start[1] + 0.5],
538 top, left, squareWidth);
540 this.computeEndArrow(
541 aStart, [arrow.end[0] + 0.5, arrow.end[1] + 0.5],
542 top, left, squareWidth);
543 const arrowWidth = squareWidth / 4;
545 document.createElementNS("http://www.w3.org/2000/svg", "path");
546 path.classList.add("svg-arrow");
549 "M" + aStart.x + "," + aStart.y + " " + "L" + aEnd.x + "," + aEnd.y
551 path.style = "stroke-width:" + arrowWidth + "px";
554 re_setDrawings: function() {
555 // Remove current canvas, if any
556 const curCanvas = document.getElementById("arrowCanvas");
557 if (!!curCanvas) curCanvas.parentNode.removeChild(curCanvas);
558 // Add some drawing on board (for some variants + arrows and circles)
559 const boardElt = document.getElementById("gamePosition");
560 const squareWidth = boardElt.offsetWidth / V.size.y;
561 const bPos = boardElt.getBoundingClientRect();
563 this.arrows.forEach(a => {
564 svgArrows.push(this.getSvgArrow(a, bPos.top, bPos.left, squareWidth));
568 V.Lines.forEach(line => {
570 this.coordsToXY(line[0], bPos.top, bPos.left, squareWidth);
572 this.coordsToXY(line[1], bPos.top, bPos.left, squareWidth);
574 document.createElementNS("http://www.w3.org/2000/svg", "path");
575 if (line[0][0] == line[1][0] || line[0][1] == line[1][1])
576 path.classList.add("svg-line");
578 // "Diagonals" are drawn with a lighter color (TODO: generalize)
579 path.classList.add("svg-diag");
582 "M" + lStart.x + "," + lStart.y + " " +
583 "L" + lEnd.x + "," + lEnd.y
589 document.createElementNS("http://www.w3.org/2000/svg", "svg");
590 arrowCanvas.id = "arrowCanvas";
591 arrowCanvas.setAttribute("stroke", "none");
593 document.createElementNS("http://www.w3.org/2000/svg", "defs");
594 const arrowWidth = squareWidth / 4;
596 document.createElementNS("http://www.w3.org/2000/svg", "marker");
598 marker.setAttribute("markerWidth", (2 * arrowWidth) + "px");
599 marker.setAttribute("markerHeight", (3 * arrowWidth) + "px");
600 marker.setAttribute("markerUnits", "userSpaceOnUse");
601 marker.setAttribute("refX", "0");
602 marker.setAttribute("refY", (1.5 * arrowWidth) + "px");
603 marker.setAttribute("orient", "auto");
605 document.createElementNS("http://www.w3.org/2000/svg", "path");
606 head.classList.add("arrow-head");
609 "M0,0 L0," + (3 * arrowWidth) + " L" +
610 (2 * arrowWidth) + "," + (1.5 * arrowWidth) + " z"
612 marker.appendChild(head);
613 defs.appendChild(marker);
614 arrowCanvas.appendChild(defs);
615 svgArrows.concat(vLines).forEach(av => arrowCanvas.appendChild(av));
616 document.getElementById("rootBoardElement").appendChild(arrowCanvas);
618 mousedown: function(e) {
620 if (!this.mobileBrowser && e.which != 3)
621 // Cancel current drawing and circles, if any
622 this.cancelResetArrows();
623 if (this.mobileBrowser || e.which == 1) {
627 document.getElementById("boardContainer").getBoundingClientRect();
628 // NOTE: classList[0] is enough: 'piece' is the first assigned class
629 const withPiece = (e.target.classList[0] == "piece");
630 // Emit the click event which could be used by some variants
633 getSquareFromId(withPiece ? e.target.parentNode.id : e.target.id)
635 // Start square must contain a piece.
636 if (!withPiece) return;
637 let parent = e.target.parentNode; //surrounding square
638 // Show possible moves if current player allowed to play
639 const startSquare = getSquareFromId(parent.id);
640 this.possibleMoves = [];
641 const color = this.analyze ? this.vr.turn : this.userColor;
642 if (this.vr.canIplay(color, startSquare))
643 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
645 // For potential drag'n drop, remember start coordinates
646 // (to center the piece on mouse cursor)
647 const rect = parent.getBoundingClientRect();
649 x: rect.x + rect.width / 2,
650 y: rect.y + rect.width / 2,
653 // Add the moving piece to the board, just after current image
654 this.selectedPiece = e.target.cloneNode();
656 this.selectedPiece.style,
658 position: "absolute",
660 display: "inline-block",
664 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
666 this.processMoveAttempt(e);
668 } else if (e.which == 3) {
669 // Mouse right button
671 document.getElementById("gamePosition").getBoundingClientRect();
673 // Next loop because of potential marks
674 while (elem.tagName == "IMG") elem = elem.parentNode;
675 this.startArrow = getSquareFromId(elem.id);
678 mousemove: function(e) {
679 if (!this.selectedPiece && !this.startArrow) return;
680 // Cancel if off boardContainer
681 const [offsetX, offsetY] =
683 ? [e.changedTouches[0].clientX, e.changedTouches[0].clientY]
684 : [e.clientX, e.clientY];
686 offsetX < this.containerPos.left ||
687 offsetX > this.containerPos.right ||
688 offsetY < this.containerPos.top ||
689 offsetY > this.containerPos.bottom
691 if (!!this.selectedPiece) {
692 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
693 delete this.selectedPiece;
694 this.selectedPiece = null;
696 this.possibleMoves = []; //in case of
698 let selected = document.querySelector(".ghost");
699 if (!!selected) selected.classList.remove("ghost");
702 this.startArrow = null;
703 this.movingArrow = null;
704 const currentArrow = document.getElementById("currentArrow");
706 currentArrow.parentNode.removeChild(currentArrow);
711 if (!!this.selectedPiece) {
712 // There is an active element: move it around
714 this.selectedPiece.style,
716 left: offsetX - this.start.x + "px",
717 top: offsetY - this.start.y + "px"
723 // Next loop because of potential marks
724 while (elem.tagName == "IMG") elem = elem.parentNode;
725 // To center the arrow in square:
726 const movingCoords = getSquareFromId(elem.id);
728 movingCoords[0] != this.startArrow[0] ||
729 movingCoords[1] != this.startArrow[1]
731 this.movingArrow = movingCoords;
732 this.drawCurrentArrow();
736 mouseup: function(e) {
738 if (this.mobileBrowser || e.which == 1) {
739 if (!this.selectedPiece) return;
740 // Drag'n drop. Selected piece is no longer needed:
741 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
742 delete this.selectedPiece;
743 this.selectedPiece = null;
744 this.processMoveAttempt(e);
745 } else if (e.which == 3) {
746 if (!this.startArrow) return;
747 // Mouse right button
748 this.movingArrow = null;
749 this.processArrowAttempt(e);
752 // Called by BaseGame after partially undoing multi-moves:
753 resetCurrentAttempt: function() {
754 this.possibleMoves = [];
757 this.selectedPiece = null;
759 processMoveAttempt: function(e) {
760 // Obtain the move from start and end squares
761 const [offsetX, offsetY] =
763 ? [e.changedTouches[0].clientX, e.changedTouches[0].clientY]
764 : [e.clientX, e.clientY];
765 let landing = document.elementFromPoint(offsetX, offsetY);
766 // Next condition: classList.contains(piece) fails because of marks
767 while (landing.tagName == "IMG") landing = landing.parentNode;
768 if (this.start.id == landing.id) {
769 if (this.click == landing.id) {
770 // Second click on same square: cancel current move
771 this.possibleMoves = [];
774 } else this.click = landing.id;
778 // OK: process move attempt, landing is a square node
779 let endSquare = getSquareFromId(landing.id);
780 let moves = this.findMatchingMoves(endSquare);
781 this.possibleMoves = [];
782 if (moves.length > 1) {
783 this.clickTime = Date.now();
784 this.choices = moves;
785 } else if (moves.length == 1) this.play(moves[0]);
786 // else: forbidden move attempt
788 processArrowAttempt: function(e) {
789 // Obtain the arrow from start and end squares
790 const [offsetX, offsetY] = [e.clientX, e.clientY];
791 let landing = document.elementFromPoint(offsetX, offsetY);
792 // Next condition: classList.contains(piece) fails because of marks
793 while (landing.tagName == "IMG") landing = landing.parentNode;
794 const landingCoords = getSquareFromId(landing.id);
796 this.startArrow[0] == landingCoords[0] &&
797 this.startArrow[1] == landingCoords[1]
799 // Draw (or erase) a circle
800 this.$set(this.circles, landing.id, !this.circles[landing.id]);
803 // OK: add arrow, landing is a new square
804 const currentArrow = document.getElementById("currentArrow");
805 currentArrow.parentNode.removeChild(currentArrow);
807 start: this.startArrow,
811 this.startArrow = null;
813 findMatchingMoves: function(endSquare) {
814 // Run through moves list and return the matching set (if promotions...)
816 this.possibleMoves.filter(m => {
817 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
821 play: function(move) {
822 this.$emit("play-move", move);
829 // SVG dynamically added, so not scoped
842 marker-end: url(#arrow)
854 <style lang="sass" scoped>
855 @import "@/styles/_board_squares_img.sass";
858 // TODO: would be cleaner to restrict width so that it doesn't overflow
859 // Commented out because pieces would disappear over the board otherwise:
864 display: inline-block
885 background-color: rgba(0,0,0,0)
888 background-color: #e6ee9c
890 background-color: skyblue
897 // NOTE: no need to set z-index here, since opacity is low
903 background-color: rgba(204, 51, 0, 0.7) !important
905 background-color: rgba(204, 51, 0, 0.9) !important
907 // TODO: no predefined highlight colors, but layers. How?
909 .hover-highlight:hover
910 // TODO: color dependant on board theme, or inner border...
911 background-color: #C571E6 !important
913 .light-square.lichess.highlight-light
914 background-color: #cdd26a
915 .dark-square.lichess.highlight-dark
916 background-color: #aaa23a
918 .light-square.chesscom.highlight-light
919 background-color: #f7f783
920 .dark-square.chesscom.highlight-dark
921 background-color: #bacb44
923 .light-square.chesstempo.highlight-light
924 background-color: #9f9fff
925 .dark-square.chesstempo.highlight-dark
926 background-color: #557fff
928 .light-square.orangecc.highlight-light
929 background-color: #fef273
930 .dark-square.orangecc.highlight-dark
931 background-color: #e8c525