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 (V.OnBoard(m.start.x, m.start.y))
64 lmHighlights[m.start.x + sizeX * m.start.y] = true;
65 if (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);
641 // For potential drag'n drop, remember start coordinates
642 // (to center the piece on mouse cursor)
643 const rect = parent.getBoundingClientRect();
645 x: rect.x + rect.width / 2,
646 y: rect.y + rect.width / 2,
649 // Add the moving piece to the board, just after current image
650 this.selectedPiece = e.target.cloneNode();
652 this.selectedPiece.style,
654 position: "absolute",
656 display: "inline-block",
660 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
662 this.processMoveAttempt(e);
664 } else if (e.which == 3) {
665 // Mouse right button
667 document.getElementById("gamePosition").getBoundingClientRect();
669 // Next loop because of potential marks
670 while (elem.tagName == "IMG") elem = elem.parentNode;
671 this.startArrow = getSquareFromId(elem.id);
674 mousemove: function(e) {
675 if (!this.selectedPiece && !this.startArrow) return;
676 // Cancel if off boardContainer
677 const [offsetX, offsetY] =
679 ? [e.changedTouches[0].clientX, e.changedTouches[0].clientY]
680 : [e.clientX, e.clientY];
682 offsetX < this.containerPos.left ||
683 offsetX > this.containerPos.right ||
684 offsetY < this.containerPos.top ||
685 offsetY > this.containerPos.bottom
687 if (!!this.selectedPiece) {
688 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
689 delete this.selectedPiece;
690 this.selectedPiece = null;
692 this.possibleMoves = []; //in case of
694 let selected = document.querySelector(".ghost");
695 if (!!selected) selected.classList.remove("ghost");
698 this.startArrow = null;
699 this.movingArrow = null;
700 const currentArrow = document.getElementById("currentArrow");
702 currentArrow.parentNode.removeChild(currentArrow);
707 if (!!this.selectedPiece) {
708 // There is an active element: move it around
710 this.selectedPiece.style,
712 left: offsetX - this.start.x + "px",
713 top: offsetY - this.start.y + "px"
719 // Next loop because of potential marks
720 while (elem.tagName == "IMG") elem = elem.parentNode;
721 // To center the arrow in square:
722 const movingCoords = getSquareFromId(elem.id);
724 movingCoords[0] != this.startArrow[0] ||
725 movingCoords[1] != this.startArrow[1]
727 this.movingArrow = movingCoords;
728 this.drawCurrentArrow();
732 mouseup: function(e) {
734 if (this.mobileBrowser || e.which == 1) {
735 if (!this.selectedPiece) return;
736 // Drag'n drop. Selected piece is no longer needed:
737 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
738 delete this.selectedPiece;
739 this.selectedPiece = null;
740 this.processMoveAttempt(e);
741 } else if (e.which == 3) {
742 if (!this.startArrow) return;
743 // Mouse right button
744 this.movingArrow = null;
745 this.processArrowAttempt(e);
748 // Called by BaseGame after partially undoing multi-moves:
749 resetCurrentAttempt: function() {
750 this.possibleMoves = [];
753 this.selectedPiece = null;
755 processMoveAttempt: function(e) {
756 // Obtain the move from start and end squares
757 const [offsetX, offsetY] =
759 ? [e.changedTouches[0].clientX, e.changedTouches[0].clientY]
760 : [e.clientX, e.clientY];
761 let landing = document.elementFromPoint(offsetX, offsetY);
762 // Next condition: classList.contains(piece) fails because of marks
763 while (landing.tagName == "IMG") landing = landing.parentNode;
764 if (this.start.id == landing.id) {
765 if (this.click == landing.id) {
766 // Second click on same square: cancel current move
767 this.possibleMoves = [];
770 } else this.click = landing.id;
774 // OK: process move attempt, landing is a square node
775 let endSquare = getSquareFromId(landing.id);
776 let moves = this.findMatchingMoves(endSquare);
777 this.possibleMoves = [];
778 if (moves.length > 1) {
779 this.clickTime = Date.now();
780 this.choices = moves;
781 } else if (moves.length == 1) this.play(moves[0]);
782 // else: forbidden move attempt
784 processArrowAttempt: function(e) {
785 // Obtain the arrow from start and end squares
786 const [offsetX, offsetY] = [e.clientX, e.clientY];
787 let landing = document.elementFromPoint(offsetX, offsetY);
788 // Next condition: classList.contains(piece) fails because of marks
789 while (landing.tagName == "IMG") landing = landing.parentNode;
790 const landingCoords = getSquareFromId(landing.id);
792 this.startArrow[0] == landingCoords[0] &&
793 this.startArrow[1] == landingCoords[1]
795 // Draw (or erase) a circle
796 this.$set(this.circles, landing.id, !this.circles[landing.id]);
799 // OK: add arrow, landing is a new square
800 const currentArrow = document.getElementById("currentArrow");
801 currentArrow.parentNode.removeChild(currentArrow);
803 start: this.startArrow,
807 this.startArrow = null;
809 findMatchingMoves: function(endSquare) {
810 // Run through moves list and return the matching set (if promotions...)
812 this.possibleMoves.filter(m => {
813 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
817 play: function(move) {
818 this.$emit("play-move", move);
825 // SVG dynamically added, so not scoped
838 marker-end: url(#arrow)
850 <style lang="sass" scoped>
851 @import "@/styles/_board_squares_img.sass";
854 // TODO: would be cleaner to restrict width so that it doesn't overflow
855 // Commented out because pieces would disappear over the board otherwise:
860 display: inline-block
881 background-color: rgba(0,0,0,0)
884 background-color: #e6ee9c
886 background-color: skyblue
893 // NOTE: no need to set z-index here, since opacity is low
899 background-color: rgba(204, 51, 0, 0.7) !important
901 background-color: rgba(204, 51, 0, 0.9) !important
903 // TODO: no predefined highlight colors, but layers. How?
905 .hover-highlight:hover
906 // TODO: color dependant on board theme, or inner border...
907 background-color: #C571E6
909 .light-square.lichess.highlight-light
910 background-color: #cdd26a
911 .dark-square.lichess.highlight-dark
912 background-color: #aaa23a
914 .light-square.chesscom.highlight-light
915 background-color: #f7f783
916 .dark-square.chesscom.highlight-dark
917 background-color: #bacb44
919 .light-square.chesstempo.highlight-light
920 background-color: #9f9fff
921 .dark-square.chesstempo.highlight-dark
922 background-color: #557fff
924 .light-square.orangecc.highlight-light
925 background-color: #fef273
926 .dark-square.orangecc.highlight-dark
927 background-color: #e8c525