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)) {
129 !!this.selectedPiece &&
130 this.selectedPiece.parentNode.id == squareId
136 this.vr.board[ci][cj],
137 // Extra args useful for some variants:
146 if (this.settings.hints && hintSquares[ci][cj]) {
153 src: "/images/mark.svg"
158 if (!!this.circles[squareId]) {
162 "circle-square": true
165 src: "/images/circle.svg"
170 const lightSquare = (ci + cj) % 2 == lightSquareMod;
176 ["board" + sizeY]: true,
177 "light-square": lightSquare && !V.Monochrome,
178 "dark-square": !lightSquare || !!V.Monochrome,
179 [this.settings.bcolor]: true,
180 "in-shadow": inShadow(ci, cj),
181 "highlight-light": inHighlight(ci, cj) && lightSquare,
182 "highlight-dark": inHighlight(ci, cj) && !lightSquare,
184 showCheck && lightSquare && incheckSq[ci][cj],
186 showCheck && !lightSquare && incheckSq[ci][cj]
189 id: getSquareId({ x: ci, y: cj })
198 if (!!this.vr.reserve) {
199 const playingColor = this.userColor || "w"; //default for an observer
200 const shiftIdx = playingColor == "w" ? 0 : 1;
201 // Some variants have more than sizeY reserve pieces (Clorange: 10)
202 const reserveSquareNb = Math.max(sizeY, V.RESERVE_PIECES.length);
203 let myReservePiecesArray = [];
204 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
205 const qty = this.vr.reserve[playingColor][V.RESERVE_PIECES[i]];
206 myReservePiecesArray.push(
210 "class": { board: true, ["board" + reserveSquareNb]: true },
211 attrs: { id: getSquareId({ x: sizeX + shiftIdx, y: i }) },
212 style: { opacity: qty > 0 ? 1 : 0.35 }
216 "class": { piece: true, reserve: true },
220 this.vr.getReservePpath(i, playingColor, orientation) +
224 h("sup", { "class": { "reserve-count": true } }, [ qty ])
229 let oppReservePiecesArray = [];
230 const oppCol = V.GetOppCol(playingColor);
231 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
232 const qty = this.vr.reserve[oppCol][V.RESERVE_PIECES[i]];
233 oppReservePiecesArray.push(
237 "class": { board: true, ["board" + reserveSquareNb]: true },
238 attrs: { id: getSquareId({ x: sizeX + (1 - shiftIdx), y: i }) },
239 style: { opacity: qty > 0 ? 1 : 0.35 }
243 "class": { piece: true, reserve: true },
247 this.vr.getReservePpath(i, oppCol, orientation) +
251 h("sup", { "class": { "reserve-count": true } }, [ qty ])
256 const myReserveTop = (
257 (playingColor == 'w' && orientation == 'b') ||
258 (playingColor == 'b' && orientation == 'w')
260 // Center reserves, assuming same number of pieces for each side:
261 const nbReservePieces = myReservePiecesArray.length;
263 ((100 - nbReservePieces * (100 / reserveSquareNb)) / 2) + "%";
273 "margin-left": marginLeft
285 myReserveTop ? myReservePiecesArray : oppReservePiecesArray
298 "margin-left": marginLeft
310 myReserveTop ? oppReservePiecesArray : myReservePiecesArray
314 elementArray.push(reserveTop);
316 elementArray.push(gameDiv);
317 if (!!this.vr.reserve) elementArray.push(reserveBottom);
318 const boardElt = document.getElementById("gamePosition");
319 // boardElt might be undefine (at first drawing)
320 if (this.choices.length > 0 && !!boardElt) {
321 const squareWidth = boardElt.offsetWidth / sizeY;
322 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
323 const maxNbeltsPerRow = Math.min(this.choices.length, sizeY);
324 let topOffset = offset[0] + (sizeY / 2) * squareWidth - squareWidth / 2;
325 let choicesHeight = squareWidth;
326 if (this.choices.length >= sizeY) {
327 // A second row is required (Eightpieces variant)
328 topOffset -= squareWidth / 2;
334 attrs: { id: "choices" },
335 "class": { row: true },
337 top: topOffset + "px",
340 (squareWidth * Math.max(sizeY - this.choices.length, 0)) / 2 +
342 width: (maxNbeltsPerRow * squareWidth) + "px",
343 height: choicesHeight + "px"
349 "class": { "full-width": true }
351 this.choices.map(m => {
352 // A "choice" is a move
353 const applyMove = (e) => {
355 // Force a delay between move is shown and clicked
356 // (otherwise a "double-click" bug might occur)
357 if (Date.now() - this.clickTime < 200) return;
363 ? { touchend: applyMove }
364 : { mouseup: applyMove };
370 ["board" + sizeY]: true
373 width: (100 / maxNbeltsPerRow) + "%",
374 "padding-bottom": (100 / maxNbeltsPerRow) + "%"
382 // orientation: extra arg useful for some variants:
383 this.vr.getPPpath(m, this.orientation) +
386 "class": { "choice-piece": true },
394 elementArray.unshift(choices);
397 // NOTE: click = mousedown + mouseup
398 if (this.mobileBrowser) {
401 touchstart: this.mousedown,
402 touchmove: this.mousemove,
403 touchend: this.mouseup
409 mousedown: this.mousedown,
410 mousemove: this.mousemove,
411 mouseup: this.mouseup,
412 contextmenu: this.blockContextMenu
419 Object.assign({ attrs: { id: "rootBoardElement" } }, onEvents),
424 updated: function() {
425 this.re_setDrawings();
428 blockContextMenu: function(e) {
433 cancelResetArrows: function() {
434 this.startArrow = null;
437 const curCanvas = document.getElementById("arrowCanvas");
438 if (!!curCanvas) curCanvas.parentNode.removeChild(curCanvas);
440 coordsToXY: function(coords, top, left, squareWidth) {
442 // [1] for x and [0] for y because conventions in rules are inversed.
444 left + window.scrollX +
447 (this.orientation == 'w' ? coords[1] : (V.size.y - coords[1]))
451 top + window.scrollY +
454 (this.orientation == 'w' ? coords[0] : (V.size.x - coords[0]))
459 computeEndArrow: function(start, end, top, left, squareWidth) {
460 const endCoords = this.coordsToXY(end, top, left, squareWidth);
461 const delta = [endCoords.x - start.x, endCoords.y - start.y];
462 const dist = Math.sqrt(delta[0] * delta[0] + delta[1] * delta[1]);
463 // Simple heuristic for now, just remove 1/3 square.
464 // TODO: should depend on the orientation.
465 const fracSqWidth = squareWidth / 3;
467 x: endCoords.x - delta[0] * fracSqWidth / dist,
468 y: endCoords.y - delta[1] * fracSqWidth / dist
471 drawCurrentArrow: function() {
472 const boardElt = document.getElementById("gamePosition");
473 const squareWidth = boardElt.offsetWidth / V.size.y;
474 const bPos = boardElt.getBoundingClientRect();
477 [this.startArrow[0] + 0.5, this.startArrow[1] + 0.5],
478 bPos.top, bPos.left, squareWidth);
480 this.computeEndArrow(
481 aStart, [this.movingArrow[0] + 0.5, this.movingArrow[1] + 0.5],
482 bPos.top, bPos.left, squareWidth);
483 let currentArrow = document.getElementById("currentArrow");
485 "M" + aStart.x + "," + aStart.y + " " + "L" + aEnd.x + "," + aEnd.y;
486 const arrowWidth = squareWidth / 4;
487 if (!!currentArrow) currentArrow.setAttribute("d", d);
490 document.createElementNS("http://www.w3.org/2000/svg", "path");
491 domArrow.classList.add("svg-arrow");
492 domArrow.id = "currentArrow";
493 domArrow.setAttribute("d", d);
494 domArrow.style = "stroke-width:" + arrowWidth + "px";
495 document.getElementById("arrowCanvas")
496 .insertAdjacentElement("beforeend", domArrow);
499 addArrow: function(arrow) {
500 this.arrows.push(arrow);
502 const boardElt = document.getElementById("gamePosition");
503 const squareWidth = boardElt.offsetWidth / V.size.y;
504 const bPos = boardElt.getBoundingClientRect();
506 this.getSvgArrow(arrow, bPos.top, bPos.left, squareWidth);
507 document.getElementById("arrowCanvas")
508 .insertAdjacentElement("beforeend", newArrow);
510 getSvgArrow: function(arrow, top, left, squareWidth) {
513 [arrow.start[0] + 0.5, arrow.start[1] + 0.5],
514 top, left, squareWidth);
516 this.computeEndArrow(
517 aStart, [arrow.end[0] + 0.5, arrow.end[1] + 0.5],
518 top, left, squareWidth);
519 const arrowWidth = squareWidth / 4;
521 document.createElementNS("http://www.w3.org/2000/svg", "path");
522 path.classList.add("svg-arrow");
525 "M" + aStart.x + "," + aStart.y + " " + "L" + aEnd.x + "," + aEnd.y
527 path.style = "stroke-width:" + arrowWidth + "px";
530 re_setDrawings: function() {
531 // Remove current canvas, if any
532 const curCanvas = document.getElementById("arrowCanvas");
533 if (!!curCanvas) curCanvas.parentNode.removeChild(curCanvas);
534 // Add some drawing on board (for some variants + arrows and circles)
535 const boardElt = document.getElementById("gamePosition");
536 const squareWidth = boardElt.offsetWidth / V.size.y;
537 const bPos = boardElt.getBoundingClientRect();
539 this.arrows.forEach(a => {
540 svgArrows.push(this.getSvgArrow(a, bPos.top, bPos.left, squareWidth));
544 V.Lines.forEach(line => {
546 this.coordsToXY(line[0], bPos.top, bPos.left, squareWidth);
548 this.coordsToXY(line[1], bPos.top, bPos.left, squareWidth);
550 document.createElementNS("http://www.w3.org/2000/svg", "path");
551 path.classList.add("svg-line");
554 "M" + lStart.x + "," + lStart.y + " " +
555 "L" + lEnd.x + "," + lEnd.y
561 document.createElementNS("http://www.w3.org/2000/svg", "svg");
562 arrowCanvas.id = "arrowCanvas";
563 arrowCanvas.setAttribute("stroke", "none");
565 document.createElementNS("http://www.w3.org/2000/svg", "defs");
566 const arrowWidth = squareWidth / 4;
568 document.createElementNS("http://www.w3.org/2000/svg", "marker");
570 marker.setAttribute("markerWidth", (2 * arrowWidth) + "px");
571 marker.setAttribute("markerHeight", (3 * arrowWidth) + "px");
572 marker.setAttribute("markerUnits", "userSpaceOnUse");
573 marker.setAttribute("refX", "0");
574 marker.setAttribute("refY", (1.5 * arrowWidth) + "px");
575 marker.setAttribute("orient", "auto");
577 document.createElementNS("http://www.w3.org/2000/svg", "path");
578 head.classList.add("arrow-head");
581 "M0,0 L0," + (3 * arrowWidth) + " L" +
582 (2 * arrowWidth) + "," + (1.5 * arrowWidth) + " z"
584 marker.appendChild(head);
585 defs.appendChild(marker);
586 arrowCanvas.appendChild(defs);
587 svgArrows.concat(vLines).forEach(av => arrowCanvas.appendChild(av));
588 document.getElementById("rootBoardElement").appendChild(arrowCanvas);
590 mousedown: function(e) {
592 if (!this.mobileBrowser && e.which != 3)
593 // Cancel current drawing and circles, if any
594 this.cancelResetArrows();
596 document.getElementById("boardContainer").getBoundingClientRect();
597 if (this.mobileBrowser || e.which == 1) {
600 // NOTE: classList[0] is enough: 'piece' is the first assigned class
601 const withPiece = (e.target.classList[0] == "piece");
602 // Emit the click event which could be used by some variants
605 getSquareFromId(withPiece ? e.target.parentNode.id : e.target.id)
607 // Start square must contain a piece.
608 if (!withPiece) return;
609 let parent = e.target.parentNode; //surrounding square
610 // Show possible moves if current player allowed to play
611 const startSquare = getSquareFromId(parent.id);
612 this.possibleMoves = [];
613 const color = this.analyze ? this.vr.turn : this.userColor;
614 if (this.vr.canIplay(color, startSquare))
615 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
616 // For potential drag'n drop, remember start coordinates
617 // (to center the piece on mouse cursor)
618 const rect = parent.getBoundingClientRect();
620 x: rect.x + rect.width / 2,
621 y: rect.y + rect.width / 2,
624 // Add the moving piece to the board, just after current image
625 this.selectedPiece = e.target.cloneNode();
627 this.selectedPiece.style,
629 position: "absolute",
631 display: "inline-block",
635 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
637 this.processMoveAttempt(e);
639 } else if (e.which == 3) {
640 // Mouse right button
642 // Next loop because of potential marks
643 while (elem.tagName == "IMG") elem = elem.parentNode;
644 this.startArrow = getSquareFromId(elem.id);
647 mousemove: function(e) {
648 if (!this.selectedPiece && !this.startArrow) return;
649 // Cancel if off boardContainer
650 const [offsetX, offsetY] =
654 e.changedTouches[0].pageX,
655 // TODO: fixing attempt for smartphones, removing window.scrollY
656 e.changedTouches[0].pageY - window.scrollY
658 : [e.clientX, e.clientY];
660 offsetX < this.containerPos.left ||
661 offsetX > this.containerPos.right ||
662 offsetY < this.containerPos.top ||
663 offsetY > this.containerPos.bottom
665 this.selectedPiece = null;
666 this.startArrow = null;
670 if (!!this.selectedPiece) {
671 // There is an active element: move it around
673 this.selectedPiece.style,
675 left: offsetX - this.start.x + "px",
676 top: offsetY - this.start.y + "px"
682 // Next loop because of potential marks
683 while (elem.tagName == "IMG") elem = elem.parentNode;
684 // To center the arrow in square:
685 const movingCoords = getSquareFromId(elem.id);
687 movingCoords[0] != this.startArrow[0] ||
688 movingCoords[1] != this.startArrow[1]
690 this.movingArrow = movingCoords;
691 this.drawCurrentArrow();
695 mouseup: function(e) {
697 if (this.mobileBrowser || e.which == 1) {
698 if (!this.selectedPiece) return;
699 // Drag'n drop. Selected piece is no longer needed:
700 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
701 delete this.selectedPiece;
702 this.selectedPiece = null;
703 this.processMoveAttempt(e);
704 } else if (e.which == 3) {
705 // Mouse right button
706 this.movingArrow = null;
707 this.processArrowAttempt(e);
710 // Called by BaseGame after partially undoing multi-moves:
711 resetCurrentAttempt: function() {
712 this.possibleMoves = [];
715 this.selectedPiece = null;
717 processMoveAttempt: function(e) {
718 // Obtain the move from start and end squares
719 const [offsetX, offsetY] =
723 e.changedTouches[0].pageX,
724 e.changedTouches[0].pageY - window.scrollY
726 : [e.clientX, e.clientY];
727 let landing = document.elementFromPoint(offsetX, offsetY);
728 // Next condition: classList.contains(piece) fails because of marks
729 while (landing.tagName == "IMG") landing = landing.parentNode;
730 if (this.start.id == landing.id) {
731 if (this.click == landing.id) {
732 // Second click on same square: cancel current move
733 this.possibleMoves = [];
736 } else this.click = landing.id;
740 // OK: process move attempt, landing is a square node
741 let endSquare = getSquareFromId(landing.id);
742 let moves = this.findMatchingMoves(endSquare);
743 this.possibleMoves = [];
744 if (moves.length > 1) {
745 this.clickTime = Date.now();
746 this.choices = moves;
747 } else if (moves.length == 1) this.play(moves[0]);
748 // else: forbidden move attempt
750 processArrowAttempt: function(e) {
751 // Obtain the arrow from start and end squares
752 const [offsetX, offsetY] = [e.clientX, e.clientY];
753 let landing = document.elementFromPoint(offsetX, offsetY);
754 // Next condition: classList.contains(piece) fails because of marks
755 while (landing.tagName == "IMG") landing = landing.parentNode;
756 const landingCoords = getSquareFromId(landing.id);
758 this.startArrow[0] == landingCoords[0] &&
759 this.startArrow[1] == landingCoords[1]
761 // Draw (or erase) a circle
762 this.$set(this.circles, landing.id, !this.circles[landing.id]);
765 // OK: add arrow, landing is a new square
766 const currentArrow = document.getElementById("currentArrow");
767 currentArrow.parentNode.removeChild(currentArrow);
769 start: this.startArrow,
773 this.startArrow = null;
775 findMatchingMoves: function(endSquare) {
776 // Run through moves list and return the matching set (if promotions...)
778 this.possibleMoves.filter(m => {
779 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
783 play: function(move) {
784 this.$emit("play-move", move);
791 // SVG dynamically added, so not scoped
804 marker-end: url(#arrow)
813 <style lang="sass" scoped>
814 @import "@/styles/_board_squares_img.sass";
816 // NOTE: no variants with reserve of size != 8
840 background-color: rgba(0,0,0,0)
843 background-color: #e6ee9c
845 background-color: skyblue
857 background-color: rgba(204, 51, 0, 0.7) !important
859 background-color: rgba(204, 51, 0, 0.9) !important
861 .light-square.lichess
862 background-color: #f0d9b5;
864 background-color: #b58863;
866 .light-square.chesscom
867 background-color: #e5e5ca;
868 .dark-square.chesscom
869 background-color: #6f8f57;
871 .light-square.chesstempo
872 background-color: #dfdfdf;
873 .dark-square.chesstempo
874 background-color: #7287b6;
876 // TODO: no predefined highlight colors, but layers. How?
878 .light-square.lichess.highlight-light
879 background-color: #cdd26a
880 .dark-square.lichess.highlight-dark
881 background-color: #aaa23a
883 .light-square.chesscom.highlight-light
884 background-color: #f7f783
885 .dark-square.chesscom.highlight-dark
886 background-color: #bacb44
888 .light-square.chesstempo.highlight-light
889 background-color: #9f9fff
890 .dark-square.chesstempo.highlight-dark
891 background-color: #557fff