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]
194 id: getSquareId({ x: ci, y: cj })
203 if (!!this.vr.reserve) {
204 const playingColor = this.userColor || "w"; //default for an observer
205 const shiftIdx = playingColor == "w" ? 0 : 1;
206 // Some variants have more than sizeY reserve pieces (Clorange: 10)
207 const reserveSquareNb = Math.max(sizeY, V.RESERVE_PIECES.length);
208 let myReservePiecesArray = [];
209 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
210 const qty = this.vr.reserve[playingColor][V.RESERVE_PIECES[i]];
211 myReservePiecesArray.push(
215 "class": { board: true, ["board" + reserveSquareNb]: true },
216 attrs: { id: getSquareId({ x: sizeX + shiftIdx, y: i }) },
217 style: { opacity: qty > 0 ? 1 : 0.35 }
221 // NOTE: class "reserve" not used currently
222 "class": { piece: true, reserve: true },
226 this.vr.getReservePpath(i, playingColor, orientation) +
233 "class": { "reserve-count": true },
234 style: { top: "calc(100% + 5px)" }
242 let oppReservePiecesArray = [];
243 const oppCol = V.GetOppCol(playingColor);
244 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
245 const qty = this.vr.reserve[oppCol][V.RESERVE_PIECES[i]];
246 oppReservePiecesArray.push(
250 "class": { board: true, ["board" + reserveSquareNb]: true },
251 attrs: { id: getSquareId({ x: sizeX + (1 - shiftIdx), y: i }) },
252 style: { opacity: qty > 0 ? 1 : 0.35 }
256 "class": { piece: true, reserve: true },
260 this.vr.getReservePpath(i, oppCol, orientation) +
267 "class": { "reserve-count": true },
268 style: { top: "calc(100% + 5px)" }
276 const myReserveTop = (
277 (playingColor == 'w' && orientation == 'b') ||
278 (playingColor == 'b' && orientation == 'w')
280 // Center reserves, assuming same number of pieces for each side:
281 const nbReservePieces = myReservePiecesArray.length;
283 ((100 - nbReservePieces * (100 / reserveSquareNb)) / 2) + "%";
293 "margin-left": marginLeft
305 myReserveTop ? myReservePiecesArray : oppReservePiecesArray
318 "margin-left": marginLeft
330 myReserveTop ? oppReservePiecesArray : myReservePiecesArray
334 elementArray.push(reserveTop);
336 elementArray.push(gameDiv);
337 if (!!this.vr.reserve) elementArray.push(reserveBottom);
338 const boardElt = document.getElementById("gamePosition");
339 // boardElt might be undefine (at first drawing)
340 if (this.choices.length > 0 && !!boardElt) {
341 const squareWidth = boardElt.offsetWidth / sizeY;
342 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
343 const maxNbeltsPerRow = Math.min(this.choices.length, sizeY);
344 let topOffset = offset[0] + (sizeY / 2) * squareWidth - squareWidth / 2;
345 let choicesHeight = squareWidth;
346 if (this.choices.length >= sizeY) {
347 // A second row is required (Eightpieces variant)
348 topOffset -= squareWidth / 2;
354 attrs: { id: "choices" },
355 "class": { row: true },
357 top: topOffset + "px",
360 (squareWidth * Math.max(sizeY - this.choices.length, 0)) / 2 +
362 width: (maxNbeltsPerRow * squareWidth) + "px",
363 height: choicesHeight + "px"
369 "class": { "full-width": true }
371 this.choices.map(m => {
372 // A "choice" is a move
373 const applyMove = (e) => {
375 // Force a delay between move is shown and clicked
376 // (otherwise a "double-click" bug might occur)
377 if (Date.now() - this.clickTime < 200) return;
383 ? { touchend: applyMove }
384 : { mouseup: applyMove };
390 ["board" + sizeY]: true
393 width: (100 / maxNbeltsPerRow) + "%",
394 "padding-bottom": (100 / maxNbeltsPerRow) + "%"
402 // orientation: extra arg useful for some variants:
403 this.vr.getPPpath(m, this.orientation) +
406 "class": { "choice-piece": true },
414 elementArray.unshift(choices);
417 // NOTE: click = mousedown + mouseup
418 if (this.mobileBrowser) {
421 touchstart: this.mousedown,
422 touchmove: this.mousemove,
423 touchend: this.mouseup
429 mousedown: this.mousedown,
430 mousemove: this.mousemove,
431 mouseup: this.mouseup,
432 contextmenu: this.blockContextMenu
439 Object.assign({ attrs: { id: "rootBoardElement" } }, onEvents),
444 updated: function() {
445 this.re_setDrawings();
448 blockContextMenu: function(e) {
453 cancelResetArrows: function() {
454 this.startArrow = null;
457 const curCanvas = document.getElementById("arrowCanvas");
458 if (!!curCanvas) curCanvas.parentNode.removeChild(curCanvas);
460 coordsToXY: function(coords, top, left, squareWidth) {
462 // [1] for x and [0] for y because conventions in rules are inversed.
464 left + window.scrollX +
467 (this.orientation == 'w' ? coords[1] : (V.size.y - coords[1]))
471 top + window.scrollY +
474 (this.orientation == 'w' ? coords[0] : (V.size.x - coords[0]))
479 computeEndArrow: function(start, end, top, left, squareWidth) {
480 const endCoords = this.coordsToXY(end, top, left, squareWidth);
481 const delta = [endCoords.x - start.x, endCoords.y - start.y];
482 const dist = Math.sqrt(delta[0] * delta[0] + delta[1] * delta[1]);
483 // Simple heuristic for now, just remove 1/3 square.
484 // TODO: should depend on the orientation.
485 const fracSqWidth = squareWidth / 3;
487 x: endCoords.x - delta[0] * fracSqWidth / dist,
488 y: endCoords.y - delta[1] * fracSqWidth / dist
491 drawCurrentArrow: function() {
492 const boardElt = document.getElementById("gamePosition");
493 const squareWidth = boardElt.offsetWidth / V.size.y;
494 const bPos = boardElt.getBoundingClientRect();
497 [this.startArrow[0] + 0.5, this.startArrow[1] + 0.5],
498 bPos.top, bPos.left, squareWidth);
500 this.computeEndArrow(
501 aStart, [this.movingArrow[0] + 0.5, this.movingArrow[1] + 0.5],
502 bPos.top, bPos.left, squareWidth);
503 let currentArrow = document.getElementById("currentArrow");
505 "M" + aStart.x + "," + aStart.y + " " + "L" + aEnd.x + "," + aEnd.y;
506 const arrowWidth = squareWidth / 4;
507 if (!!currentArrow) currentArrow.setAttribute("d", d);
510 document.createElementNS("http://www.w3.org/2000/svg", "path");
511 domArrow.classList.add("svg-arrow");
512 domArrow.id = "currentArrow";
513 domArrow.setAttribute("d", d);
514 domArrow.style = "stroke-width:" + arrowWidth + "px";
515 document.getElementById("arrowCanvas")
516 .insertAdjacentElement("beforeend", domArrow);
519 addArrow: function(arrow) {
520 this.arrows.push(arrow);
522 const boardElt = document.getElementById("gamePosition");
523 const squareWidth = boardElt.offsetWidth / V.size.y;
524 const bPos = boardElt.getBoundingClientRect();
526 this.getSvgArrow(arrow, bPos.top, bPos.left, squareWidth);
527 document.getElementById("arrowCanvas")
528 .insertAdjacentElement("beforeend", newArrow);
530 getSvgArrow: function(arrow, top, left, squareWidth) {
533 [arrow.start[0] + 0.5, arrow.start[1] + 0.5],
534 top, left, squareWidth);
536 this.computeEndArrow(
537 aStart, [arrow.end[0] + 0.5, arrow.end[1] + 0.5],
538 top, left, squareWidth);
539 const arrowWidth = squareWidth / 4;
541 document.createElementNS("http://www.w3.org/2000/svg", "path");
542 path.classList.add("svg-arrow");
545 "M" + aStart.x + "," + aStart.y + " " + "L" + aEnd.x + "," + aEnd.y
547 path.style = "stroke-width:" + arrowWidth + "px";
550 re_setDrawings: function() {
551 // Remove current canvas, if any
552 const curCanvas = document.getElementById("arrowCanvas");
553 if (!!curCanvas) curCanvas.parentNode.removeChild(curCanvas);
554 // Add some drawing on board (for some variants + arrows and circles)
555 const boardElt = document.getElementById("gamePosition");
556 const squareWidth = boardElt.offsetWidth / V.size.y;
557 const bPos = boardElt.getBoundingClientRect();
559 this.arrows.forEach(a => {
560 svgArrows.push(this.getSvgArrow(a, bPos.top, bPos.left, squareWidth));
564 V.Lines.forEach(line => {
566 this.coordsToXY(line[0], bPos.top, bPos.left, squareWidth);
568 this.coordsToXY(line[1], bPos.top, bPos.left, squareWidth);
570 document.createElementNS("http://www.w3.org/2000/svg", "path");
571 path.classList.add("svg-line");
574 "M" + lStart.x + "," + lStart.y + " " +
575 "L" + lEnd.x + "," + lEnd.y
581 document.createElementNS("http://www.w3.org/2000/svg", "svg");
582 arrowCanvas.id = "arrowCanvas";
583 arrowCanvas.setAttribute("stroke", "none");
585 document.createElementNS("http://www.w3.org/2000/svg", "defs");
586 const arrowWidth = squareWidth / 4;
588 document.createElementNS("http://www.w3.org/2000/svg", "marker");
590 marker.setAttribute("markerWidth", (2 * arrowWidth) + "px");
591 marker.setAttribute("markerHeight", (3 * arrowWidth) + "px");
592 marker.setAttribute("markerUnits", "userSpaceOnUse");
593 marker.setAttribute("refX", "0");
594 marker.setAttribute("refY", (1.5 * arrowWidth) + "px");
595 marker.setAttribute("orient", "auto");
597 document.createElementNS("http://www.w3.org/2000/svg", "path");
598 head.classList.add("arrow-head");
601 "M0,0 L0," + (3 * arrowWidth) + " L" +
602 (2 * arrowWidth) + "," + (1.5 * arrowWidth) + " z"
604 marker.appendChild(head);
605 defs.appendChild(marker);
606 arrowCanvas.appendChild(defs);
607 svgArrows.concat(vLines).forEach(av => arrowCanvas.appendChild(av));
608 document.getElementById("rootBoardElement").appendChild(arrowCanvas);
610 mousedown: function(e) {
612 if (!this.mobileBrowser && e.which != 3)
613 // Cancel current drawing and circles, if any
614 this.cancelResetArrows();
615 if (this.mobileBrowser || e.which == 1) {
619 document.getElementById("boardContainer").getBoundingClientRect();
620 // NOTE: classList[0] is enough: 'piece' is the first assigned class
621 const withPiece = (e.target.classList[0] == "piece");
622 // Emit the click event which could be used by some variants
625 getSquareFromId(withPiece ? e.target.parentNode.id : e.target.id)
627 // Start square must contain a piece.
628 if (!withPiece) return;
629 let parent = e.target.parentNode; //surrounding square
630 // Show possible moves if current player allowed to play
631 const startSquare = getSquareFromId(parent.id);
632 this.possibleMoves = [];
633 const color = this.analyze ? this.vr.turn : this.userColor;
634 if (this.vr.canIplay(color, startSquare))
635 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
636 // For potential drag'n drop, remember start coordinates
637 // (to center the piece on mouse cursor)
638 const rect = parent.getBoundingClientRect();
640 x: rect.x + rect.width / 2,
641 y: rect.y + rect.width / 2,
644 // Add the moving piece to the board, just after current image
645 this.selectedPiece = e.target.cloneNode();
647 this.selectedPiece.style,
649 position: "absolute",
651 display: "inline-block",
655 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
657 this.processMoveAttempt(e);
659 } else if (e.which == 3) {
660 // Mouse right button
662 document.getElementById("gamePosition").getBoundingClientRect();
664 // Next loop because of potential marks
665 while (elem.tagName == "IMG") elem = elem.parentNode;
666 this.startArrow = getSquareFromId(elem.id);
669 mousemove: function(e) {
670 if (!this.selectedPiece && !this.startArrow) return;
671 // Cancel if off boardContainer
672 const [offsetX, offsetY] =
676 e.changedTouches[0].pageX,
677 // TODO: fixing attempt for smartphones, removing window.scrollY
678 e.changedTouches[0].pageY - window.scrollY
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] =
761 e.changedTouches[0].pageX,
762 e.changedTouches[0].pageY - window.scrollY
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)
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 .light-square.lichess
905 background-color: #f0d9b5
907 background-color: #b58863
909 .light-square.chesscom
910 background-color: #e5e5ca
911 .dark-square.chesscom
912 background-color: #6f8f57
914 .light-square.chesstempo
915 background-color: #dfdfdf
916 .dark-square.chesstempo
917 background-color: #7287b6
919 .middle-square.lichess
920 background-color: #D3B18C
922 .middle-square.chesscom
923 background-color: #AABA91
925 .middle-square.chesstempo
926 background-color: #A9B3CB
928 // TODO: no predefined highlight colors, but layers. How?
930 .light-square.lichess.highlight-light
931 background-color: #cdd26a
932 .dark-square.lichess.highlight-dark
933 background-color: #aaa23a
935 .light-square.chesscom.highlight-light
936 background-color: #f7f783
937 .dark-square.chesscom.highlight-dark
938 background-color: #bacb44
940 .light-square.chesstempo.highlight-light
941 background-color: #9f9fff
942 .dark-square.chesstempo.highlight-dark
943 background-color: #557fff