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 oddity = (ci + cj) % 2;
175 const lightSquare = (
176 (!V.DarkBottomRight && oddity == lightSquareMod) ||
177 (V.DarkBottomRight && oddity != lightSquareMod)
184 ["board" + sizeY]: true,
186 !V.Notoodark && lightSquare && !V.Monochrome,
188 !V.Notoodark && (!lightSquare || !!V.Monochrome),
189 "middle-square": V.Notoodark,
190 [this.settings.bcolor]: true,
191 "in-shadow": inShadow(ci, cj),
192 "highlight": inHighlight(ci, cj),
194 showCheck && lightSquare && incheckSq[ci][cj],
196 showCheck && !lightSquare && incheckSq[ci][cj],
197 "hover-highlight": this.vr.hoverHighlight(ci, cj)
200 id: getSquareId({ x: ci, y: cj })
209 if (!!this.vr.reserve) {
210 const playingColor = this.userColor || "w"; //default for an observer
211 const shiftIdx = playingColor == "w" ? 0 : 1;
212 // Some variants have more than sizeY reserve pieces (Clorange: 10)
213 const reserveSquareNb = Math.max(sizeY, V.RESERVE_PIECES.length);
214 let myReservePiecesArray = [];
215 if (!!this.vr.reserve[playingColor]) {
216 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
217 const qty = this.vr.reserve[playingColor][V.RESERVE_PIECES[i]];
218 myReservePiecesArray.push(
222 "class": { board: true, ["board" + reserveSquareNb]: true },
223 attrs: { id: getSquareId({ x: sizeX + shiftIdx, y: i }) },
224 style: { opacity: qty > 0 ? 1 : 0.35 }
228 // NOTE: class "reserve" not used currently
229 "class": { piece: true, reserve: true },
233 this.vr.getReservePpath(i, playingColor, orientation) +
240 "class": { "reserve-count": true },
241 style: { top: "calc(100% + 5px)" }
250 let oppReservePiecesArray = [];
251 const oppCol = V.GetOppCol(playingColor);
252 if (!!this.vr.reserve[oppCol]) {
253 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
254 const qty = this.vr.reserve[oppCol][V.RESERVE_PIECES[i]];
255 oppReservePiecesArray.push(
259 "class": { board: true, ["board" + reserveSquareNb]: true },
260 attrs: { id: getSquareId({ x: sizeX + (1 - shiftIdx), y: i }) },
261 style: { opacity: qty > 0 ? 1 : 0.35 }
265 "class": { piece: true, reserve: true },
269 this.vr.getReservePpath(i, oppCol, orientation) +
276 "class": { "reserve-count": true },
277 style: { top: "calc(100% + 5px)" }
286 const myReserveTop = (
287 (playingColor == 'w' && orientation == 'b') ||
288 (playingColor == 'b' && orientation == 'w')
290 const hasReserveTop = (
291 (myReserveTop && !!this.vr.reserve[playingColor]) ||
292 (!myReserveTop && !!this.vr.reserve[oppCol])
294 // "var" because must be reachable from outside this block
295 var hasReserveBottom = (
296 (myReserveTop && !!this.vr.reserve[oppCol]) ||
297 (!myReserveTop && !!this.vr.reserve[playingColor])
299 // Center reserves, assuming same number of pieces for each side:
300 const nbReservePieces = myReservePiecesArray.length;
302 ((100 - nbReservePieces * (100 / reserveSquareNb)) / 2) + "%";
313 "margin-left": marginLeft
325 myReserveTop ? myReservePiecesArray : oppReservePiecesArray
330 if (hasReserveBottom) {
340 "margin-left": marginLeft
352 myReserveTop ? oppReservePiecesArray : myReservePiecesArray
357 if (hasReserveTop) elementArray.push(reserveTop);
359 elementArray.push(gameDiv);
360 if (!!this.vr.reserve && hasReserveBottom)
361 elementArray.push(reserveBottom);
362 const boardElt = document.getElementById("gamePosition");
363 // boardElt might be undefine (at first drawing)
364 if (this.choices.length > 0 && !!boardElt) {
365 const squareWidth = boardElt.offsetWidth / sizeY;
366 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
367 const maxNbeltsPerRow = Math.min(this.choices.length, sizeY);
368 let topOffset = offset[0] + (sizeY / 2) * squareWidth - squareWidth / 2;
369 let choicesHeight = squareWidth;
370 if (this.choices.length >= sizeY) {
371 // A second row is required (Eightpieces variant)
372 topOffset -= squareWidth / 2;
378 attrs: { id: "choices" },
379 "class": { row: true },
381 top: topOffset + "px",
384 (squareWidth * Math.max(sizeY - this.choices.length, 0)) / 2 +
386 width: (maxNbeltsPerRow * squareWidth) + "px",
387 height: choicesHeight + "px"
393 "class": { "full-width": true }
395 this.choices.map(m => {
396 // A "choice" is a move
397 const applyMove = (e) => {
399 // Force a delay between move is shown and clicked
400 // (otherwise a "double-click" bug might occur)
401 if (Date.now() - this.clickTime < 200) return;
405 const stopPropagation = (e) => { e.stopPropagation(); }
408 // Must cancel mousedown logic:
409 ? { touchstart: stopPropagation, touchend: applyMove }
410 : { mousedown: stopPropagation, mouseup: applyMove };
416 ["board" + sizeY]: true
419 width: (100 / maxNbeltsPerRow) + "%",
420 "padding-bottom": (100 / maxNbeltsPerRow) + "%"
428 // orientation: extra arg useful for some variants
429 this.vr.getPPpath(m, this.orientation) +
432 "class": { "choice-piece": true },
440 elementArray.unshift(choices);
443 // NOTE: click = mousedown + mouseup
444 if (this.mobileBrowser) {
447 touchstart: this.mousedown,
448 touchmove: this.mousemove,
449 touchend: this.mouseup
456 mousedown: this.mousedown,
457 mousemove: this.mousemove,
458 mouseup: this.mouseup,
459 contextmenu: this.blockContextMenu
466 Object.assign({ attrs: { id: "rootBoardElement" } }, onEvents),
471 updated: function() {
472 this.re_setDrawings();
475 blockContextMenu: function(e) {
480 cancelResetArrows: function() {
481 this.startArrow = null;
484 const curCanvas = document.getElementById("arrowCanvas");
485 if (!!curCanvas) curCanvas.parentNode.removeChild(curCanvas);
487 coordsToXY: function(coords, top, left, squareWidth) {
489 // [1] for x and [0] for y because conventions in rules are inversed.
491 left + window.scrollX +
494 (this.orientation == 'w' ? coords[1] : (V.size.y - coords[1]))
498 top + window.scrollY +
501 (this.orientation == 'w' ? coords[0] : (V.size.x - coords[0]))
506 computeEndArrow: function(start, end, top, left, squareWidth) {
507 const endCoords = this.coordsToXY(end, top, left, squareWidth);
508 const delta = [endCoords.x - start.x, endCoords.y - start.y];
509 const dist = Math.sqrt(delta[0] * delta[0] + delta[1] * delta[1]);
510 // Simple heuristic for now, just remove 1/3 square.
511 // TODO: should depend on the orientation.
512 const fracSqWidth = squareWidth / 3;
514 x: endCoords.x - delta[0] * fracSqWidth / dist,
515 y: endCoords.y - delta[1] * fracSqWidth / dist
518 drawCurrentArrow: function() {
519 const boardElt = document.getElementById("gamePosition");
520 const squareWidth = boardElt.offsetWidth / V.size.y;
521 const bPos = boardElt.getBoundingClientRect();
524 [this.startArrow[0] + 0.5, this.startArrow[1] + 0.5],
525 bPos.top, bPos.left, squareWidth);
527 this.computeEndArrow(
528 aStart, [this.movingArrow[0] + 0.5, this.movingArrow[1] + 0.5],
529 bPos.top, bPos.left, squareWidth);
530 let currentArrow = document.getElementById("currentArrow");
532 "M" + aStart.x + "," + aStart.y + " " + "L" + aEnd.x + "," + aEnd.y;
533 const arrowWidth = squareWidth / 4;
534 if (!!currentArrow) currentArrow.setAttribute("d", d);
537 document.createElementNS("http://www.w3.org/2000/svg", "path");
538 domArrow.classList.add("svg-arrow");
539 domArrow.id = "currentArrow";
540 domArrow.setAttribute("d", d);
541 domArrow.style = "stroke-width:" + arrowWidth + "px";
542 document.getElementById("arrowCanvas")
543 .insertAdjacentElement("beforeend", domArrow);
546 addArrow: function(arrow) {
547 this.arrows.push(arrow);
549 const boardElt = document.getElementById("gamePosition");
550 const squareWidth = boardElt.offsetWidth / V.size.y;
551 const bPos = boardElt.getBoundingClientRect();
553 this.getSvgArrow(arrow, bPos.top, bPos.left, squareWidth);
554 document.getElementById("arrowCanvas")
555 .insertAdjacentElement("beforeend", newArrow);
557 getSvgArrow: function(arrow, top, left, squareWidth) {
560 [arrow.start[0] + 0.5, arrow.start[1] + 0.5],
561 top, left, squareWidth);
563 this.computeEndArrow(
564 aStart, [arrow.end[0] + 0.5, arrow.end[1] + 0.5],
565 top, left, squareWidth);
566 const arrowWidth = squareWidth / 4;
568 document.createElementNS("http://www.w3.org/2000/svg", "path");
569 path.classList.add("svg-arrow");
572 "M" + aStart.x + "," + aStart.y + " " + "L" + aEnd.x + "," + aEnd.y
574 path.style = "stroke-width:" + arrowWidth + "px";
577 re_setDrawings: function() {
578 // Remove current canvas, if any
579 const curCanvas = document.getElementById("arrowCanvas");
580 if (!!curCanvas) curCanvas.parentNode.removeChild(curCanvas);
581 // Add some drawing on board (for some variants + arrows and circles)
582 const boardElt = document.getElementById("gamePosition");
583 const squareWidth = boardElt.offsetWidth / V.size.y;
584 const bPos = boardElt.getBoundingClientRect();
586 this.arrows.forEach(a => {
587 svgArrows.push(this.getSvgArrow(a, bPos.top, bPos.left, squareWidth));
591 V.Lines.forEach(line => {
593 this.coordsToXY(line[0], bPos.top, bPos.left, squareWidth);
595 this.coordsToXY(line[1], bPos.top, bPos.left, squareWidth);
597 document.createElementNS("http://www.w3.org/2000/svg", "path");
598 if (line[0][0] == line[1][0] || line[0][1] == line[1][1])
599 path.classList.add("svg-line");
601 // "Diagonals" are drawn with a lighter color (TODO: generalize)
602 path.classList.add("svg-diag");
605 "M" + lStart.x + "," + lStart.y + " " +
606 "L" + lEnd.x + "," + lEnd.y
612 document.createElementNS("http://www.w3.org/2000/svg", "svg");
613 arrowCanvas.id = "arrowCanvas";
614 arrowCanvas.setAttribute("stroke", "none");
616 document.createElementNS("http://www.w3.org/2000/svg", "defs");
617 const arrowWidth = squareWidth / 4;
619 document.createElementNS("http://www.w3.org/2000/svg", "marker");
621 marker.setAttribute("markerWidth", (2 * arrowWidth) + "px");
622 marker.setAttribute("markerHeight", (3 * arrowWidth) + "px");
623 marker.setAttribute("markerUnits", "userSpaceOnUse");
624 marker.setAttribute("refX", "0");
625 marker.setAttribute("refY", (1.5 * arrowWidth) + "px");
626 marker.setAttribute("orient", "auto");
628 document.createElementNS("http://www.w3.org/2000/svg", "path");
629 head.classList.add("arrow-head");
632 "M0,0 L0," + (3 * arrowWidth) + " L" +
633 (2 * arrowWidth) + "," + (1.5 * arrowWidth) + " z"
635 marker.appendChild(head);
636 defs.appendChild(marker);
637 arrowCanvas.appendChild(defs);
638 svgArrows.concat(vLines).forEach(av => arrowCanvas.appendChild(av));
639 document.getElementById("rootBoardElement").appendChild(arrowCanvas);
641 mousedown: function(e) {
643 if (!this.mobileBrowser && e.which != 3)
644 // Cancel current drawing and circles, if any
645 this.cancelResetArrows();
646 if (this.mobileBrowser || e.which == 1) {
650 document.getElementById("boardContainer").getBoundingClientRect();
651 // NOTE: classList[0] is enough: 'piece' is the first assigned class
652 const withPiece = (e.target.classList[0] == "piece");
653 // Show possible moves if current player allowed to play
655 getSquareFromId(withPiece ? e.target.parentNode.id : e.target.id);
656 this.possibleMoves = [];
657 const color = this.analyze ? this.vr.turn : this.userColor;
658 if (this.vr.canIplay(color, startSquare)) {
659 // Emit the click event which could be used by some variants
661 (withPiece ? e.target.parentNode.id : e.target.id);
662 const sq = getSquareFromId(targetId);
663 this.$emit("click-square", sq);
664 if (withPiece && !this.vr.onlyClick(sq)) {
665 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
666 // For potential drag'n drop, remember start coordinates
667 // (to center the piece on mouse cursor)
668 let parent = e.target.parentNode; //surrounding square
669 const rect = parent.getBoundingClientRect();
671 x: rect.x + rect.width / 2,
672 y: rect.y + rect.width / 2,
675 // Add the moving piece to the board, just after current image
676 this.selectedPiece = e.target.cloneNode();
678 this.selectedPiece.style,
680 position: "absolute",
682 display: "inline-block",
686 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
690 else this.processMoveAttempt(e);
692 else if (e.which == 3) {
693 // Mouse right button
695 document.getElementById("gamePosition").getBoundingClientRect();
697 // Next loop because of potential marks
698 while (elem.tagName == "IMG") elem = elem.parentNode;
699 this.startArrow = getSquareFromId(elem.id);
702 mousemove: function(e) {
703 if (!this.selectedPiece && !this.startArrow) return;
704 // Cancel if off boardContainer
705 const [offsetX, offsetY] =
707 ? [e.changedTouches[0].clientX, e.changedTouches[0].clientY]
708 : [e.clientX, e.clientY];
710 offsetX < this.containerPos.left ||
711 offsetX > this.containerPos.right ||
712 offsetY < this.containerPos.top ||
713 offsetY > this.containerPos.bottom
715 if (!!this.selectedPiece) {
716 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
717 delete this.selectedPiece;
718 this.selectedPiece = null;
720 this.possibleMoves = []; //in case of
722 let selected = document.querySelector(".ghost");
723 if (!!selected) selected.classList.remove("ghost");
726 this.startArrow = null;
727 this.movingArrow = null;
728 const currentArrow = document.getElementById("currentArrow");
730 currentArrow.parentNode.removeChild(currentArrow);
735 if (!!this.selectedPiece) {
736 // There is an active element: move it around
738 this.selectedPiece.style,
740 left: offsetX - this.start.x + "px",
741 top: offsetY - this.start.y + "px"
747 // Next loop because of potential marks
748 while (elem.tagName == "IMG") elem = elem.parentNode;
749 // To center the arrow in square:
750 const movingCoords = getSquareFromId(elem.id);
752 movingCoords[0] != this.startArrow[0] ||
753 movingCoords[1] != this.startArrow[1]
755 this.movingArrow = movingCoords;
756 this.drawCurrentArrow();
760 mouseup: function(e) {
762 if (this.mobileBrowser || e.which == 1) {
763 if (!this.selectedPiece) return;
764 // Drag'n drop. Selected piece is no longer needed:
765 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
766 delete this.selectedPiece;
767 this.selectedPiece = null;
768 this.processMoveAttempt(e);
769 } else if (e.which == 3) {
770 if (!this.startArrow) return;
771 // Mouse right button
772 this.movingArrow = null;
773 this.processArrowAttempt(e);
776 // Called by BaseGame after partially undoing multi-moves:
777 resetCurrentAttempt: function() {
778 this.possibleMoves = [];
781 this.selectedPiece = null;
783 processMoveAttempt: function(e) {
784 // Obtain the move from start and end squares
785 const [offsetX, offsetY] =
787 ? [e.changedTouches[0].clientX, e.changedTouches[0].clientY]
788 : [e.clientX, e.clientY];
789 let landing = document.elementFromPoint(offsetX, offsetY);
790 // Next condition: classList.contains(piece) fails because of marks
791 while (landing.tagName == "IMG") landing = landing.parentNode;
792 if (this.start.id == landing.id) {
793 if (this.click == landing.id) {
794 // Second click on same square: cancel current move
795 this.possibleMoves = [];
798 } else this.click = landing.id;
802 // OK: process move attempt, landing is a square node
803 let endSquare = getSquareFromId(landing.id);
804 let moves = this.findMatchingMoves(endSquare);
805 this.possibleMoves = [];
806 if (moves.length > 1) {
807 this.clickTime = Date.now();
808 this.choices = moves;
809 } else if (moves.length == 1) this.play(moves[0]);
810 // else: forbidden move attempt
812 processArrowAttempt: function(e) {
813 // Obtain the arrow from start and end squares
814 const [offsetX, offsetY] = [e.clientX, e.clientY];
815 let landing = document.elementFromPoint(offsetX, offsetY);
816 // Next condition: classList.contains(piece) fails because of marks
817 while (landing.tagName == "IMG") landing = landing.parentNode;
818 const landingCoords = getSquareFromId(landing.id);
820 this.startArrow[0] == landingCoords[0] &&
821 this.startArrow[1] == landingCoords[1]
823 // Draw (or erase) a circle
824 this.$set(this.circles, landing.id, !this.circles[landing.id]);
827 // OK: add arrow, landing is a new square
828 const currentArrow = document.getElementById("currentArrow");
829 currentArrow.parentNode.removeChild(currentArrow);
831 start: this.startArrow,
835 this.startArrow = null;
837 findMatchingMoves: function(endSquare) {
838 // Run through moves list and return the matching set (if promotions...)
840 this.possibleMoves.filter(m => {
841 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
845 play: function(move) {
846 this.$emit("play-move", move);
853 // SVG dynamically added, so not scoped
866 marker-end: url(#arrow)
878 <style lang="sass" scoped>
879 @import "@/styles/_board_squares_img.sass";
882 // TODO: would be cleaner to restrict width so that it doesn't overflow
883 // Commented out because pieces would disappear over the board otherwise:
888 display: inline-block
909 background-color: rgba(0,0,0,0)
912 background-color: #e6ee9c
914 background-color: skyblue
921 // NOTE: no need to set z-index here, since opacity is low
927 background-color: rgba(204, 51, 0, 0.7) !important
929 background-color: rgba(204, 51, 0, 0.9) !important
931 // TODO: no predefined highlight colors, but layers. How?
933 .hover-highlight:hover
934 // TODO: color dependant on board theme, or inner border...
935 background-color: #C571E6 !important
940 background-color: #cdd26a
942 background-color: #f7f783
944 background-color: #9f9fff
946 background-color: #fef273
949 background-color: #aaa23a
951 background-color: #bacb44
953 background-color: #557fff
955 background-color: #e8c525
958 background-color: #BCBA52
960 background-color: #D9E164
962 background-color: #7A8FFF
964 background-color: #F3DC4C