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;
70 this.settings.highlight &&
71 ["all", "highlight"].includes(V.ShowMoves)
74 this.settings.highlight &&
75 ["all", "highlight", "byrow"].includes(V.ShowMoves)
77 const orientation = !V.CanFlip ? "w" : this.orientation;
78 // Ensure that squares colors do not change when board is flipped
79 const lightSquareMod = (sizeX + sizeY) % 2;
80 const showPiece = (x, y) => {
82 this.vr.board[x][y] != V.EMPTY &&
83 (!this.vr.enlightened || this.analyze || this.score != "*" ||
84 (!!this.userColor && this.vr.enlightened[this.userColor][x][y]))
87 const inHighlight = (x, y) => {
88 return showLight && !!lmHighlights[x + sizeX * y];
90 const inShadow = (x, y) => {
94 this.vr.enlightened &&
95 (!this.userColor || !this.vr.enlightened[this.userColor][x][y])
98 // Create board element (+ reserves if needed by variant)
99 let elementArray = [];
103 attrs: { id: "gamePosition" },
109 [...Array(sizeX).keys()].map(i => {
110 const ci = orientation == "w" ? i : sizeX - i - 1;
117 style: { opacity: this.choices.length > 0 ? "0.5" : "1" }
119 [...Array(sizeY).keys()].map(j => {
120 const cj = orientation == "w" ? j : sizeY - j - 1;
121 const squareId = "sq-" + ci + "-" + cj;
123 if (showPiece(ci, cj)) {
128 !!this.selectedPiece &&
129 this.selectedPiece.parentNode.id == squareId
135 this.vr.board[ci][cj],
136 // Extra args useful for some variants:
143 if (this.arrows.length == 0)
144 pieceSpecs["style"] = { position: "absolute" };
145 elems.push(h("img", pieceSpecs));
147 if (this.settings.hints && hintSquares[ci][cj]) {
154 src: "/images/mark.svg"
159 if (!!this.circles[squareId]) {
163 "circle-square": true
166 src: "/images/circle.svg"
171 const lightSquare = (ci + cj) % 2 == lightSquareMod;
177 ["board" + sizeY]: true,
179 !V.Notoodark && lightSquare && !V.Monochrome,
181 !V.Notoodark && (!lightSquare || !!V.Monochrome),
182 "middle-square": V.Notoodark,
183 [this.settings.bcolor]: true,
184 "in-shadow": inShadow(ci, cj),
185 "highlight-light": inHighlight(ci, cj) && lightSquare,
187 inHighlight(ci, cj) && (V.Monochrome || !lightSquare),
189 showCheck && lightSquare && incheckSq[ci][cj],
191 showCheck && !lightSquare && incheckSq[ci][cj],
192 "hover-highlight": this.vr.hoverHighlight(ci, cj)
195 id: getSquareId({ x: ci, y: cj })
204 if (!!this.vr.reserve) {
205 const playingColor = this.userColor || "w"; //default for an observer
206 const shiftIdx = playingColor == "w" ? 0 : 1;
207 // Some variants have more than sizeY reserve pieces (Clorange: 10)
208 const reserveSquareNb = Math.max(sizeY, V.RESERVE_PIECES.length);
209 let myReservePiecesArray = [];
210 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
211 const qty = this.vr.reserve[playingColor][V.RESERVE_PIECES[i]];
212 myReservePiecesArray.push(
216 "class": { board: true, ["board" + reserveSquareNb]: true },
217 attrs: { id: getSquareId({ x: sizeX + shiftIdx, y: i }) },
218 style: { opacity: qty > 0 ? 1 : 0.35 }
222 // NOTE: class "reserve" not used currently
223 "class": { piece: true, reserve: true },
227 this.vr.getReservePpath(i, playingColor, orientation) +
234 "class": { "reserve-count": true },
235 style: { top: "calc(100% + 5px)" }
243 let oppReservePiecesArray = [];
244 const oppCol = V.GetOppCol(playingColor);
245 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
246 const qty = this.vr.reserve[oppCol][V.RESERVE_PIECES[i]];
247 oppReservePiecesArray.push(
251 "class": { board: true, ["board" + reserveSquareNb]: true },
252 attrs: { id: getSquareId({ x: sizeX + (1 - shiftIdx), y: i }) },
253 style: { opacity: qty > 0 ? 1 : 0.35 }
257 "class": { piece: true, reserve: true },
261 this.vr.getReservePpath(i, oppCol, orientation) +
268 "class": { "reserve-count": true },
269 style: { top: "calc(100% + 5px)" }
277 const myReserveTop = (
278 (playingColor == 'w' && orientation == 'b') ||
279 (playingColor == 'b' && orientation == 'w')
281 // Center reserves, assuming same number of pieces for each side:
282 const nbReservePieces = myReservePiecesArray.length;
284 ((100 - nbReservePieces * (100 / reserveSquareNb)) / 2) + "%";
294 "margin-left": marginLeft
306 myReserveTop ? myReservePiecesArray : oppReservePiecesArray
319 "margin-left": marginLeft
331 myReserveTop ? oppReservePiecesArray : myReservePiecesArray
335 elementArray.push(reserveTop);
337 elementArray.push(gameDiv);
338 if (!!this.vr.reserve) elementArray.push(reserveBottom);
339 const boardElt = document.getElementById("gamePosition");
340 // boardElt might be undefine (at first drawing)
341 if (this.choices.length > 0 && !!boardElt) {
342 const squareWidth = boardElt.offsetWidth / sizeY;
343 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
344 const maxNbeltsPerRow = Math.min(this.choices.length, sizeY);
345 let topOffset = offset[0] + (sizeY / 2) * squareWidth - squareWidth / 2;
346 let choicesHeight = squareWidth;
347 if (this.choices.length >= sizeY) {
348 // A second row is required (Eightpieces variant)
349 topOffset -= squareWidth / 2;
355 attrs: { id: "choices" },
356 "class": { row: true },
358 top: topOffset + "px",
361 (squareWidth * Math.max(sizeY - this.choices.length, 0)) / 2 +
363 width: (maxNbeltsPerRow * squareWidth) + "px",
364 height: choicesHeight + "px"
370 "class": { "full-width": true }
372 this.choices.map(m => {
373 // A "choice" is a move
374 const applyMove = (e) => {
376 // Force a delay between move is shown and clicked
377 // (otherwise a "double-click" bug might occur)
378 if (Date.now() - this.clickTime < 200) return;
384 ? { touchend: applyMove }
385 : { mouseup: applyMove };
391 ["board" + sizeY]: true
394 width: (100 / maxNbeltsPerRow) + "%",
395 "padding-bottom": (100 / maxNbeltsPerRow) + "%"
403 // orientation: extra arg useful for some variants:
404 this.vr.getPPpath(m, this.orientation) +
407 "class": { "choice-piece": true },
415 elementArray.unshift(choices);
418 // NOTE: click = mousedown + mouseup
419 if (this.mobileBrowser) {
422 touchstart: this.mousedown,
423 touchmove: this.mousemove,
424 touchend: this.mouseup
430 mousedown: this.mousedown,
431 mousemove: this.mousemove,
432 mouseup: this.mouseup,
433 contextmenu: this.blockContextMenu
440 Object.assign({ attrs: { id: "rootBoardElement" } }, onEvents),
445 updated: function() {
446 this.re_setDrawings();
449 blockContextMenu: function(e) {
454 cancelResetArrows: function() {
455 this.startArrow = null;
458 const curCanvas = document.getElementById("arrowCanvas");
459 if (!!curCanvas) curCanvas.parentNode.removeChild(curCanvas);
461 coordsToXY: function(coords, top, left, squareWidth) {
463 // [1] for x and [0] for y because conventions in rules are inversed.
465 left + window.scrollX +
468 (this.orientation == 'w' ? coords[1] : (V.size.y - coords[1]))
472 top + window.scrollY +
475 (this.orientation == 'w' ? coords[0] : (V.size.x - coords[0]))
480 computeEndArrow: function(start, end, top, left, squareWidth) {
481 const endCoords = this.coordsToXY(end, top, left, squareWidth);
482 const delta = [endCoords.x - start.x, endCoords.y - start.y];
483 const dist = Math.sqrt(delta[0] * delta[0] + delta[1] * delta[1]);
484 // Simple heuristic for now, just remove 1/3 square.
485 // TODO: should depend on the orientation.
486 const fracSqWidth = squareWidth / 3;
488 x: endCoords.x - delta[0] * fracSqWidth / dist,
489 y: endCoords.y - delta[1] * fracSqWidth / dist
492 drawCurrentArrow: function() {
493 const boardElt = document.getElementById("gamePosition");
494 const squareWidth = boardElt.offsetWidth / V.size.y;
495 const bPos = boardElt.getBoundingClientRect();
498 [this.startArrow[0] + 0.5, this.startArrow[1] + 0.5],
499 bPos.top, bPos.left, squareWidth);
501 this.computeEndArrow(
502 aStart, [this.movingArrow[0] + 0.5, this.movingArrow[1] + 0.5],
503 bPos.top, bPos.left, squareWidth);
504 let currentArrow = document.getElementById("currentArrow");
506 "M" + aStart.x + "," + aStart.y + " " + "L" + aEnd.x + "," + aEnd.y;
507 const arrowWidth = squareWidth / 4;
508 if (!!currentArrow) currentArrow.setAttribute("d", d);
511 document.createElementNS("http://www.w3.org/2000/svg", "path");
512 domArrow.classList.add("svg-arrow");
513 domArrow.id = "currentArrow";
514 domArrow.setAttribute("d", d);
515 domArrow.style = "stroke-width:" + arrowWidth + "px";
516 document.getElementById("arrowCanvas")
517 .insertAdjacentElement("beforeend", domArrow);
520 addArrow: function(arrow) {
521 this.arrows.push(arrow);
523 const boardElt = document.getElementById("gamePosition");
524 const squareWidth = boardElt.offsetWidth / V.size.y;
525 const bPos = boardElt.getBoundingClientRect();
527 this.getSvgArrow(arrow, bPos.top, bPos.left, squareWidth);
528 document.getElementById("arrowCanvas")
529 .insertAdjacentElement("beforeend", newArrow);
531 getSvgArrow: function(arrow, top, left, squareWidth) {
534 [arrow.start[0] + 0.5, arrow.start[1] + 0.5],
535 top, left, squareWidth);
537 this.computeEndArrow(
538 aStart, [arrow.end[0] + 0.5, arrow.end[1] + 0.5],
539 top, left, squareWidth);
540 const arrowWidth = squareWidth / 4;
542 document.createElementNS("http://www.w3.org/2000/svg", "path");
543 path.classList.add("svg-arrow");
546 "M" + aStart.x + "," + aStart.y + " " + "L" + aEnd.x + "," + aEnd.y
548 path.style = "stroke-width:" + arrowWidth + "px";
551 re_setDrawings: function() {
552 // Remove current canvas, if any
553 const curCanvas = document.getElementById("arrowCanvas");
554 if (!!curCanvas) curCanvas.parentNode.removeChild(curCanvas);
555 // Add some drawing on board (for some variants + arrows and circles)
556 const boardElt = document.getElementById("gamePosition");
557 const squareWidth = boardElt.offsetWidth / V.size.y;
558 const bPos = boardElt.getBoundingClientRect();
560 this.arrows.forEach(a => {
561 svgArrows.push(this.getSvgArrow(a, bPos.top, bPos.left, squareWidth));
565 V.Lines.forEach(line => {
567 this.coordsToXY(line[0], bPos.top, bPos.left, squareWidth);
569 this.coordsToXY(line[1], bPos.top, bPos.left, squareWidth);
571 document.createElementNS("http://www.w3.org/2000/svg", "path");
572 if (line[0][0] == line[1][0] || line[0][1] == line[1][1])
573 path.classList.add("svg-line");
575 // "Diagonals" are drawn with a lighter color (TODO: generalize)
576 path.classList.add("svg-diag");
579 "M" + lStart.x + "," + lStart.y + " " +
580 "L" + lEnd.x + "," + lEnd.y
586 document.createElementNS("http://www.w3.org/2000/svg", "svg");
587 arrowCanvas.id = "arrowCanvas";
588 arrowCanvas.setAttribute("stroke", "none");
590 document.createElementNS("http://www.w3.org/2000/svg", "defs");
591 const arrowWidth = squareWidth / 4;
593 document.createElementNS("http://www.w3.org/2000/svg", "marker");
595 marker.setAttribute("markerWidth", (2 * arrowWidth) + "px");
596 marker.setAttribute("markerHeight", (3 * arrowWidth) + "px");
597 marker.setAttribute("markerUnits", "userSpaceOnUse");
598 marker.setAttribute("refX", "0");
599 marker.setAttribute("refY", (1.5 * arrowWidth) + "px");
600 marker.setAttribute("orient", "auto");
602 document.createElementNS("http://www.w3.org/2000/svg", "path");
603 head.classList.add("arrow-head");
606 "M0,0 L0," + (3 * arrowWidth) + " L" +
607 (2 * arrowWidth) + "," + (1.5 * arrowWidth) + " z"
609 marker.appendChild(head);
610 defs.appendChild(marker);
611 arrowCanvas.appendChild(defs);
612 svgArrows.concat(vLines).forEach(av => arrowCanvas.appendChild(av));
613 document.getElementById("rootBoardElement").appendChild(arrowCanvas);
615 mousedown: function(e) {
617 if (!this.mobileBrowser && e.which != 3)
618 // Cancel current drawing and circles, if any
619 this.cancelResetArrows();
620 if (this.mobileBrowser || e.which == 1) {
624 document.getElementById("boardContainer").getBoundingClientRect();
625 // NOTE: classList[0] is enough: 'piece' is the first assigned class
626 const withPiece = (e.target.classList[0] == "piece");
627 // Emit the click event which could be used by some variants
630 getSquareFromId(withPiece ? e.target.parentNode.id : e.target.id)
632 // Start square must contain a piece.
633 if (!withPiece) return;
634 let parent = e.target.parentNode; //surrounding square
635 // Show possible moves if current player allowed to play
636 const startSquare = getSquareFromId(parent.id);
637 this.possibleMoves = [];
638 const color = this.analyze ? this.vr.turn : this.userColor;
639 if (this.vr.canIplay(color, startSquare))
640 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
642 // For potential drag'n drop, remember start coordinates
643 // (to center the piece on mouse cursor)
644 const rect = parent.getBoundingClientRect();
646 x: rect.x + rect.width / 2,
647 y: rect.y + rect.width / 2,
650 // Add the moving piece to the board, just after current image
651 this.selectedPiece = e.target.cloneNode();
653 this.selectedPiece.style,
655 position: "absolute",
657 display: "inline-block",
661 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
663 this.processMoveAttempt(e);
665 } else if (e.which == 3) {
666 // Mouse right button
668 document.getElementById("gamePosition").getBoundingClientRect();
670 // Next loop because of potential marks
671 while (elem.tagName == "IMG") elem = elem.parentNode;
672 this.startArrow = getSquareFromId(elem.id);
675 mousemove: function(e) {
676 if (!this.selectedPiece && !this.startArrow) return;
677 // Cancel if off boardContainer
678 const [offsetX, offsetY] =
680 ? [e.changedTouches[0].clientX, e.changedTouches[0].clientY]
681 : [e.clientX, e.clientY];
683 offsetX < this.containerPos.left ||
684 offsetX > this.containerPos.right ||
685 offsetY < this.containerPos.top ||
686 offsetY > this.containerPos.bottom
688 if (!!this.selectedPiece) {
689 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
690 delete this.selectedPiece;
691 this.selectedPiece = null;
693 this.possibleMoves = []; //in case of
695 let selected = document.querySelector(".ghost");
696 if (!!selected) selected.classList.remove("ghost");
699 this.startArrow = null;
700 this.movingArrow = null;
701 const currentArrow = document.getElementById("currentArrow");
703 currentArrow.parentNode.removeChild(currentArrow);
708 if (!!this.selectedPiece) {
709 // There is an active element: move it around
711 this.selectedPiece.style,
713 left: offsetX - this.start.x + "px",
714 top: offsetY - this.start.y + "px"
720 // Next loop because of potential marks
721 while (elem.tagName == "IMG") elem = elem.parentNode;
722 // To center the arrow in square:
723 const movingCoords = getSquareFromId(elem.id);
725 movingCoords[0] != this.startArrow[0] ||
726 movingCoords[1] != this.startArrow[1]
728 this.movingArrow = movingCoords;
729 this.drawCurrentArrow();
733 mouseup: function(e) {
735 if (this.mobileBrowser || e.which == 1) {
736 if (!this.selectedPiece) return;
737 // Drag'n drop. Selected piece is no longer needed:
738 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
739 delete this.selectedPiece;
740 this.selectedPiece = null;
741 this.processMoveAttempt(e);
742 } else if (e.which == 3) {
743 if (!this.startArrow) return;
744 // Mouse right button
745 this.movingArrow = null;
746 this.processArrowAttempt(e);
749 // Called by BaseGame after partially undoing multi-moves:
750 resetCurrentAttempt: function() {
751 this.possibleMoves = [];
754 this.selectedPiece = null;
756 processMoveAttempt: function(e) {
757 // Obtain the move from start and end squares
758 const [offsetX, offsetY] =
760 ? [e.changedTouches[0].clientX, e.changedTouches[0].clientY]
761 : [e.clientX, e.clientY];
762 let landing = document.elementFromPoint(offsetX, offsetY);
763 // Next condition: classList.contains(piece) fails because of marks
764 while (landing.tagName == "IMG") landing = landing.parentNode;
765 if (this.start.id == landing.id) {
766 if (this.click == landing.id) {
767 // Second click on same square: cancel current move
768 this.possibleMoves = [];
771 } else this.click = landing.id;
775 // OK: process move attempt, landing is a square node
776 let endSquare = getSquareFromId(landing.id);
777 let moves = this.findMatchingMoves(endSquare);
778 this.possibleMoves = [];
779 if (moves.length > 1) {
780 this.clickTime = Date.now();
781 this.choices = moves;
782 } else if (moves.length == 1) this.play(moves[0]);
783 // else: forbidden move attempt
785 processArrowAttempt: function(e) {
786 // Obtain the arrow from start and end squares
787 const [offsetX, offsetY] = [e.clientX, e.clientY];
788 let landing = document.elementFromPoint(offsetX, offsetY);
789 // Next condition: classList.contains(piece) fails because of marks
790 while (landing.tagName == "IMG") landing = landing.parentNode;
791 const landingCoords = getSquareFromId(landing.id);
793 this.startArrow[0] == landingCoords[0] &&
794 this.startArrow[1] == landingCoords[1]
796 // Draw (or erase) a circle
797 this.$set(this.circles, landing.id, !this.circles[landing.id]);
800 // OK: add arrow, landing is a new square
801 const currentArrow = document.getElementById("currentArrow");
802 currentArrow.parentNode.removeChild(currentArrow);
804 start: this.startArrow,
808 this.startArrow = null;
810 findMatchingMoves: function(endSquare) {
811 // Run through moves list and return the matching set (if promotions...)
813 this.possibleMoves.filter(m => {
814 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
818 play: function(move) {
819 this.$emit("play-move", move);
826 // SVG dynamically added, so not scoped
839 marker-end: url(#arrow)
851 <style lang="sass" scoped>
852 @import "@/styles/_board_squares_img.sass";
855 // TODO: would be cleaner to restrict width so that it doesn't overflow
856 // Commented out because pieces would disappear over the board otherwise:
861 display: inline-block
882 background-color: rgba(0,0,0,0)
885 background-color: #e6ee9c
887 background-color: skyblue
894 // NOTE: no need to set z-index here, since opacity is low
900 background-color: rgba(204, 51, 0, 0.7) !important
902 background-color: rgba(204, 51, 0, 0.9) !important
904 // TODO: no predefined highlight colors, but layers. How?
906 .hover-highlight:hover
907 // TODO: color dependant on board theme, or inner border...
908 background-color: #C571E6 !important
910 .light-square.lichess.highlight-light
911 background-color: #cdd26a
912 .dark-square.lichess.highlight-dark
913 background-color: #aaa23a
915 .light-square.chesscom.highlight-light
916 background-color: #f7f783
917 .dark-square.chesscom.highlight-dark
918 background-color: #bacb44
920 .light-square.chesstempo.highlight-light
921 background-color: #9f9fff
922 .dark-square.chesstempo.highlight-dark
923 background-color: #557fff
925 .light-square.orangecc.highlight-light
926 background-color: #fef273
927 .dark-square.orangecc.highlight-dark
928 background-color: #e8c525