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?)
35 settings: store.state.settings
40 // Return empty div of class 'game' to avoid error when setting size
43 { "class": { game: true } }
46 const [sizeX, sizeY] = [V.size.x, V.size.y];
47 // Precompute hints squares to facilitate rendering
48 let hintSquares = ArrayFun.init(sizeX, sizeY, false);
49 this.possibleMoves.forEach(m => {
50 hintSquares[m.end.x][m.end.y] = true;
52 // Also precompute in-check squares
53 let incheckSq = ArrayFun.init(sizeX, sizeY, false);
54 this.incheck.forEach(sq => {
55 incheckSq[sq[0]][sq[1]] = true;
58 let lm = this.lastMove;
59 // Precompute lastMove highlighting squares
60 const lmHighlights = {};
62 if (!Array.isArray(lm)) lm = [lm];
64 if (!m.start.noHighlight && V.OnBoard(m.start.x, m.start.y))
65 lmHighlights[m.start.x + sizeX * m.start.y] = true;
66 if (!m.end.noHighlight && V.OnBoard(m.end.x, m.end.y))
67 lmHighlights[m.end.x + sizeX * m.end.y] = true;
69 // For Dice variant (at least?)
70 lmHighlights[m.start.toplay[0] + sizeX * m.start.toplay[1]] = true;
74 this.settings.highlight &&
75 ["all", "highlight"].includes(V.ShowMoves)
78 this.settings.highlight &&
79 ["all", "highlight", "byrow"].includes(V.ShowMoves)
81 const orientation = !V.CanFlip ? "w" : this.orientation;
82 // Ensure that squares colors do not change when board is flipped
83 const lightSquareMod = (sizeX + sizeY) % 2;
84 const showPiece = (x, y) => {
86 this.vr.board[x][y] != V.EMPTY &&
87 (!this.vr.enlightened || this.analyze || this.score != "*" ||
88 (!!this.userColor && this.vr.enlightened[this.userColor][x][y]))
91 const inHighlight = (x, y) => {
92 return showLight && !!lmHighlights[x + sizeX * y];
94 const inShadow = (x, y) => {
98 this.vr.enlightened &&
99 (!this.userColor || !this.vr.enlightened[this.userColor][x][y])
102 // Create board element (+ reserves if needed by variant)
103 let elementArray = [];
107 attrs: { id: "gamePosition" },
113 [...Array(sizeX).keys()].map(i => {
114 const ci = orientation == "w" ? i : sizeX - i - 1;
121 style: { opacity: this.choices.length > 0 ? "0.5" : "1" }
123 [...Array(sizeY).keys()].map(j => {
124 const cj = orientation == "w" ? j : sizeY - j - 1;
125 const squareId = "sq-" + ci + "-" + cj;
127 if (showPiece(ci, cj)) {
132 !!this.selectedPiece &&
133 this.selectedPiece.parentNode.id == squareId
139 this.vr.board[ci][cj],
140 // Extra args useful for some variants:
147 if (this.arrows.length == 0)
148 pieceSpecs["style"] = { position: "absolute" };
149 elems.push(h("img", pieceSpecs));
151 if (this.settings.hints && hintSquares[ci][cj]) {
158 src: "/images/mark.svg"
163 if (!!this.circles[squareId]) {
167 "circle-square": true
170 src: "/images/circle.svg"
175 const oddity = (ci + cj) % 2;
176 const lightSquare = (
177 (!V.DarkBottomRight && oddity == lightSquareMod) ||
178 (V.DarkBottomRight && oddity != lightSquareMod)
185 ["board" + sizeY]: true,
187 !V.Notoodark && lightSquare && !V.Monochrome,
189 !V.Notoodark && (!lightSquare || !!V.Monochrome),
190 "middle-square": V.Notoodark,
191 [this.settings.bcolor]: true,
192 "in-shadow": inShadow(ci, cj),
193 "highlight": inHighlight(ci, cj),
195 showCheck && lightSquare && incheckSq[ci][cj],
197 showCheck && !lightSquare && incheckSq[ci][cj],
199 this.vr.hoverHighlight(
200 [ci, cj], !this.analyze ? this.userColor : null)
203 id: getSquareId({ x: ci, y: cj })
212 if (!!this.vr.reserve) {
213 const playingColor = this.userColor || "w"; //default for an observer
214 const shiftIdx = playingColor == "w" ? 0 : 1;
215 // Some variants have more than sizeY reserve pieces (Clorange: 10)
216 const reserveSquareNb = Math.max(sizeY, V.RESERVE_PIECES.length);
217 let myReservePiecesArray = [];
218 if (!!this.vr.reserve[playingColor]) {
219 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
220 const qty = this.vr.reserve[playingColor][V.RESERVE_PIECES[i]];
221 myReservePiecesArray.push(
225 "class": { board: true, ["board" + reserveSquareNb]: true },
226 attrs: { id: getSquareId({ x: sizeX + shiftIdx, y: i }) },
227 style: { opacity: qty > 0 ? 1 : 0.35 }
231 // NOTE: class "reserve" not used currently
232 "class": { piece: true, reserve: true },
236 this.vr.getReservePpath(i, playingColor, orientation) +
243 "class": { "reserve-count": true },
244 style: { top: "calc(100% + 5px)" }
253 let oppReservePiecesArray = [];
254 const oppCol = V.GetOppCol(playingColor);
255 if (!!this.vr.reserve[oppCol]) {
256 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
257 const qty = this.vr.reserve[oppCol][V.RESERVE_PIECES[i]];
258 oppReservePiecesArray.push(
262 "class": { board: true, ["board" + reserveSquareNb]: true },
263 attrs: { id: getSquareId({ x: sizeX + (1 - shiftIdx), y: i }) },
264 style: { opacity: qty > 0 ? 1 : 0.35 }
268 "class": { piece: true, reserve: true },
272 this.vr.getReservePpath(i, oppCol, orientation) +
279 "class": { "reserve-count": true },
280 style: { top: "calc(100% + 5px)" }
289 const myReserveTop = (
290 (playingColor == 'w' && orientation == 'b') ||
291 (playingColor == 'b' && orientation == 'w')
293 const hasReserveTop = (
294 (myReserveTop && !!this.vr.reserve[playingColor]) ||
295 (!myReserveTop && !!this.vr.reserve[oppCol])
297 // "var" because must be reachable from outside this block
298 var hasReserveBottom = (
299 (myReserveTop && !!this.vr.reserve[oppCol]) ||
300 (!myReserveTop && !!this.vr.reserve[playingColor])
302 // Center reserves, assuming same number of pieces for each side:
303 const nbReservePieces =
304 Math.max(myReservePiecesArray.length, oppReservePiecesArray.length);
306 ((100 - nbReservePieces * (100 / reserveSquareNb)) / 2) + "%";
317 "margin-left": marginLeft
329 myReserveTop ? myReservePiecesArray : oppReservePiecesArray
334 if (hasReserveBottom) {
344 "margin-left": marginLeft
356 myReserveTop ? oppReservePiecesArray : myReservePiecesArray
361 if (hasReserveTop) elementArray.push(reserveTop);
363 elementArray.push(gameDiv);
364 if (!!this.vr.reserve && hasReserveBottom)
365 elementArray.push(reserveBottom);
366 const boardElt = document.getElementById("gamePosition");
367 // boardElt might be undefine (at first drawing)
368 if (this.choices.length > 0 && !!boardElt) {
369 const squareWidth = boardElt.offsetWidth / sizeY;
370 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
371 const maxNbeltsPerRow = Math.min(this.choices.length, sizeY);
372 let topOffset = offset[0] + ((sizeX - 1) / 2) * squareWidth;
373 let choicesHeight = squareWidth;
374 if (this.choices.length >= sizeY) {
375 // A second row is required (Eightpieces variant)
376 topOffset -= squareWidth / 2;
382 attrs: { id: "choices" },
383 "class": { row: true },
385 top: topOffset + "px",
388 (squareWidth * Math.max(sizeY - this.choices.length, 0)) / 2 +
390 width: (maxNbeltsPerRow * squareWidth) + "px",
391 height: choicesHeight + "px"
397 "class": { "full-width": true }
399 this.choices.map(m => {
400 // A "choice" is a move
401 const applyMove = (e) => {
403 // Force a delay between move is shown and clicked
404 // (otherwise a "double-click" bug might occur)
405 if (Date.now() - this.clickTime < 200) return;
409 const stopPropagation = (e) => { e.stopPropagation(); }
412 // Must cancel mousedown logic:
413 ? { touchstart: stopPropagation, touchend: applyMove }
414 : { mousedown: stopPropagation, mouseup: applyMove };
420 ["board" + sizeY]: true
423 width: (100 / maxNbeltsPerRow) + "%",
424 "padding-bottom": (100 / maxNbeltsPerRow) + "%"
432 // orientation: extra arg useful for some variants
433 this.vr.getPPpath(m, this.orientation) +
436 "class": { "choice-piece": true },
444 elementArray.unshift(choices);
447 // NOTE: click = mousedown + mouseup
448 if (this.mobileBrowser) {
451 touchstart: this.mousedown,
452 touchmove: this.mousemove,
453 touchend: this.mouseup
460 mousedown: this.mousedown,
461 mousemove: this.mousemove,
462 mouseup: this.mouseup,
463 contextmenu: this.blockContextMenu
467 if (this.initialized == 1) this.$emit("rendered");
468 if (this.initialized <= 1) this.initialized++;
472 Object.assign({ attrs: { id: "rootBoardElement" } }, onEvents),
477 updated: function() {
478 this.re_setDrawings();
481 blockContextMenu: function(e) {
486 cancelResetArrows: function() {
487 this.startArrow = null;
490 const curCanvas = document.getElementById("arrowCanvas");
491 if (!!curCanvas) curCanvas.parentNode.removeChild(curCanvas);
493 coordsToXY: function(coords, top, left, squareWidth) {
495 // [1] for x and [0] for y because conventions in rules are inversed.
497 left + window.scrollX +
500 (this.orientation == 'w' ? coords[1] : (V.size.y - coords[1]))
504 top + window.scrollY +
507 (this.orientation == 'w' ? coords[0] : (V.size.x - coords[0]))
512 computeEndArrow: function(start, end, top, left, squareWidth) {
513 const endCoords = this.coordsToXY(end, top, left, squareWidth);
514 const delta = [endCoords.x - start.x, endCoords.y - start.y];
515 const dist = Math.sqrt(delta[0] * delta[0] + delta[1] * delta[1]);
516 // Simple heuristic for now, just remove 1/3 square.
517 // TODO: should depend on the orientation.
518 const fracSqWidth = squareWidth / 3;
520 x: endCoords.x - delta[0] * fracSqWidth / dist,
521 y: endCoords.y - delta[1] * fracSqWidth / dist
524 drawCurrentArrow: function() {
525 const boardElt = document.getElementById("gamePosition");
526 const squareWidth = boardElt.offsetWidth / V.size.y;
527 const bPos = boardElt.getBoundingClientRect();
530 [this.startArrow[0] + 0.5, this.startArrow[1] + 0.5],
531 bPos.top, bPos.left, squareWidth);
533 this.computeEndArrow(
534 aStart, [this.movingArrow[0] + 0.5, this.movingArrow[1] + 0.5],
535 bPos.top, bPos.left, squareWidth);
536 let currentArrow = document.getElementById("currentArrow");
538 "M" + aStart.x + "," + aStart.y + " " + "L" + aEnd.x + "," + aEnd.y;
539 const arrowWidth = squareWidth / 4;
540 if (!!currentArrow) currentArrow.setAttribute("d", d);
543 document.createElementNS("http://www.w3.org/2000/svg", "path");
544 domArrow.classList.add("svg-arrow");
545 domArrow.id = "currentArrow";
546 domArrow.setAttribute("d", d);
547 domArrow.style = "stroke-width:" + arrowWidth + "px";
548 document.getElementById("arrowCanvas")
549 .insertAdjacentElement("beforeend", domArrow);
552 addArrow: function(arrow) {
553 const arrowIdx = this.arrows.findIndex(a => {
555 a.start[0] == arrow.start[0] && a.start[1] == arrow.start[1] &&
556 a.end[0] == arrow.end[0] && a.end[1] == arrow.end[1]
561 this.arrows.splice(arrowIdx, 1);
563 // Add to arrows vector:
564 this.arrows.push(arrow);
565 // NOTE: no need to draw here, will be re-draw
566 // by updated() hook callong re_setDrawings()
568 getSvgArrow: function(arrow, top, left, squareWidth) {
571 [arrow.start[0] + 0.5, arrow.start[1] + 0.5],
572 top, left, squareWidth);
574 this.computeEndArrow(
575 aStart, [arrow.end[0] + 0.5, arrow.end[1] + 0.5],
576 top, left, squareWidth);
577 const arrowWidth = squareWidth / 4;
579 document.createElementNS("http://www.w3.org/2000/svg", "path");
580 path.classList.add("svg-arrow");
583 "M" + aStart.x + "," + aStart.y + " " + "L" + aEnd.x + "," + aEnd.y
585 path.style = "stroke-width:" + arrowWidth + "px";
588 re_setDrawings: function() {
589 // Add some drawing on board (for some variants + arrows and circles)
590 const boardElt = document.getElementById("gamePosition");
591 if (!boardElt) return;
592 // Remove current canvas, if any
593 const curCanvas = document.getElementById("arrowCanvas");
594 if (!!curCanvas) curCanvas.parentNode.removeChild(curCanvas);
595 const squareWidth = boardElt.offsetWidth / V.size.y;
596 const bPos = boardElt.getBoundingClientRect();
598 this.arrows.forEach(a => {
599 svgArrows.push(this.getSvgArrow(a, bPos.top, bPos.left, squareWidth));
603 V.Lines.forEach(line => {
605 this.coordsToXY(line[0], bPos.top, bPos.left, squareWidth);
607 this.coordsToXY(line[1], bPos.top, bPos.left, squareWidth);
609 document.createElementNS("http://www.w3.org/2000/svg", "path");
610 if (line[0][0] == line[1][0] || line[0][1] == line[1][1])
611 path.classList.add("svg-line");
613 // "Diagonals" are drawn with a lighter color (TODO: generalize)
614 path.classList.add("svg-diag");
617 "M" + lStart.x + "," + lStart.y + " " +
618 "L" + lEnd.x + "," + lEnd.y
624 document.createElementNS("http://www.w3.org/2000/svg", "svg");
625 arrowCanvas.id = "arrowCanvas";
626 arrowCanvas.setAttribute("stroke", "none");
628 document.createElementNS("http://www.w3.org/2000/svg", "defs");
629 const arrowWidth = squareWidth / 4;
631 document.createElementNS("http://www.w3.org/2000/svg", "marker");
633 marker.setAttribute("markerWidth", (2 * arrowWidth) + "px");
634 marker.setAttribute("markerHeight", (3 * arrowWidth) + "px");
635 marker.setAttribute("markerUnits", "userSpaceOnUse");
636 marker.setAttribute("refX", "0");
637 marker.setAttribute("refY", (1.5 * arrowWidth) + "px");
638 marker.setAttribute("orient", "auto");
640 document.createElementNS("http://www.w3.org/2000/svg", "path");
641 head.classList.add("arrow-head");
644 "M0,0 L0," + (3 * arrowWidth) + " L" +
645 (2 * arrowWidth) + "," + (1.5 * arrowWidth) + " z"
647 marker.appendChild(head);
648 defs.appendChild(marker);
649 arrowCanvas.appendChild(defs);
650 svgArrows.concat(vLines).forEach(av => arrowCanvas.appendChild(av));
651 document.getElementById("rootBoardElement").appendChild(arrowCanvas);
653 mousedown: function(e) {
654 if (!this.mobileBrowser && e.which != 3)
655 // Cancel current drawing and circles, if any
656 this.cancelResetArrows();
657 if (this.mobileBrowser || e.which == 1) {
661 document.getElementById("boardContainer").getBoundingClientRect();
662 // NOTE: classList[0] is enough: 'piece' is the first assigned class
663 const withPiece = (e.target.classList[0] == "piece");
664 if (withPiece) e.preventDefault();
665 // Show possible moves if current player allowed to play
667 getSquareFromId(withPiece ? e.target.parentNode.id : e.target.id);
668 this.possibleMoves = [];
669 const color = this.analyze ? this.vr.turn : this.userColor;
670 if (this.vr.canIplay(color, startSquare)) {
671 // Emit the click event which could be used by some variants
673 (withPiece ? e.target.parentNode.id : e.target.id);
674 const sq = getSquareFromId(targetId);
675 this.$emit("click-square", sq);
676 if (withPiece && !this.vr.onlyClick(sq)) {
677 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
678 if (this.possibleMoves.length > 0) {
679 // For potential drag'n drop, remember start coordinates
680 // (to center the piece on mouse cursor)
681 let parent = e.target.parentNode; //surrounding square
682 const rect = parent.getBoundingClientRect();
684 x: rect.x + rect.width / 2,
685 y: rect.y + rect.width / 2,
688 // Add the moving piece to the board, just after current image
689 this.selectedPiece = e.target.cloneNode();
691 this.selectedPiece.style,
693 position: "absolute",
695 display: "inline-block",
699 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
704 else this.processMoveAttempt(e);
706 else if (e.which == 3) {
707 // Mouse right button
710 document.getElementById("gamePosition").getBoundingClientRect();
712 // Next loop because of potential marks
713 while (elem.tagName == "IMG") elem = elem.parentNode;
714 this.startArrow = getSquareFromId(elem.id);
716 else e.preventDefault();
718 mousemove: function(e) {
719 if (!this.selectedPiece && !this.startArrow) return;
720 // Cancel if off boardContainer
721 const [offsetX, offsetY] =
723 ? [e.changedTouches[0].clientX, e.changedTouches[0].clientY]
724 : [e.clientX, e.clientY];
726 offsetX < this.containerPos.left ||
727 offsetX > this.containerPos.right ||
728 offsetY < this.containerPos.top ||
729 offsetY > this.containerPos.bottom
731 if (!!this.selectedPiece) {
732 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
733 delete this.selectedPiece;
734 this.selectedPiece = null;
736 this.possibleMoves = []; //in case of
738 let selected = document.querySelector(".ghost");
739 if (!!selected) selected.classList.remove("ghost");
742 this.startArrow = null;
743 this.movingArrow = null;
744 const currentArrow = document.getElementById("currentArrow");
746 currentArrow.parentNode.removeChild(currentArrow);
751 if (!!this.selectedPiece) {
752 // There is an active element: move it around
754 this.selectedPiece.style,
756 left: offsetX - this.start.x + "px",
757 top: offsetY - this.start.y + "px"
763 // Next loop because of potential marks
764 while (elem.tagName == "IMG") elem = elem.parentNode;
765 // To center the arrow in square:
766 const movingCoords = getSquareFromId(elem.id);
768 movingCoords[0] != this.startArrow[0] ||
769 movingCoords[1] != this.startArrow[1]
771 this.movingArrow = movingCoords;
772 this.drawCurrentArrow();
776 mouseup: function(e) {
777 if (this.mobileBrowser || e.which == 1) {
778 if (!this.selectedPiece) return;
780 // Drag'n drop. Selected piece is no longer needed:
781 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
782 delete this.selectedPiece;
783 this.selectedPiece = null;
784 this.processMoveAttempt(e);
786 else if (e.which == 3) {
788 if (!this.startArrow) return;
789 // Mouse right button
790 this.movingArrow = null;
791 this.processArrowAttempt(e);
794 // Called by BaseGame after partially undoing multi-moves:
795 resetCurrentAttempt: function() {
796 this.possibleMoves = [];
799 this.selectedPiece = null;
801 processMoveAttempt: function(e) {
802 // Obtain the move from start and end squares
803 const [offsetX, offsetY] =
805 ? [e.changedTouches[0].clientX, e.changedTouches[0].clientY]
806 : [e.clientX, e.clientY];
807 let landing = document.elementFromPoint(offsetX, offsetY);
808 // Next condition: classList.contains(piece) fails because of marks
809 while (landing.tagName == "IMG") landing = landing.parentNode;
810 if (this.start.id == landing.id) {
811 if (this.click == landing.id) {
812 // Second click on same square: cancel current move
813 this.possibleMoves = [];
816 } else this.click = landing.id;
820 // OK: process move attempt, landing is a square node
821 let endSquare = getSquareFromId(landing.id);
822 let moves = this.findMatchingMoves(endSquare);
823 this.possibleMoves = [];
824 if (moves.length > 1) {
825 this.clickTime = Date.now();
826 this.choices = moves;
827 } else if (moves.length == 1) this.play(moves[0]);
828 // else: forbidden move attempt
830 processArrowAttempt: function(e) {
831 // Obtain the arrow from start and end squares
832 const [offsetX, offsetY] = [e.clientX, e.clientY];
833 let landing = document.elementFromPoint(offsetX, offsetY);
834 // Next condition: classList.contains(piece) fails because of marks
835 while (landing.tagName == "IMG") landing = landing.parentNode;
836 const landingCoords = getSquareFromId(landing.id);
838 this.startArrow[0] == landingCoords[0] &&
839 this.startArrow[1] == landingCoords[1]
841 // Draw (or erase) a circle
842 this.$set(this.circles, landing.id, !this.circles[landing.id]);
845 // OK: add arrow, landing is a new square
846 const currentArrow = document.getElementById("currentArrow");
847 currentArrow.parentNode.removeChild(currentArrow);
849 start: this.startArrow,
853 this.startArrow = null;
855 findMatchingMoves: function(endSquare) {
856 // Run through moves list and return the matching set (if promotions...)
858 this.possibleMoves.filter(m => {
859 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
863 play: function(move) {
864 this.$emit("play-move", move);
871 // SVG dynamically added, so not scoped
884 marker-end: url(#arrow)
896 <style lang="sass" scoped>
897 @import "@/styles/_board_squares_img.sass"
900 // TODO: would be cleaner to restrict width so that it doesn't overflow
901 // Commented out because pieces would disappear over the board otherwise:
906 display: inline-block
927 background-color: rgba(0,0,0,0)
930 background-color: #e6ee9c
932 background-color: skyblue
939 // NOTE: no need to set z-index here, since opacity is low
945 background-color: rgba(204, 51, 0, 0.7) !important
947 background-color: rgba(204, 51, 0, 0.9) !important
949 // TODO: no predefined highlight colors, but layers. How?
951 .hover-highlight:hover
952 // TODO: color dependant on board theme, or inner border...
953 background-color: #C571E6 !important
958 background-color: #cdd26a
960 background-color: #f7f783
962 background-color: #9f9fff
964 background-color: #fef273
967 background-color: #aaa23a
969 background-color: #bacb44
971 background-color: #557fff
973 background-color: #e8c525
976 background-color: #BCBA52
978 background-color: #D9E164
980 background-color: #7A8FFF
982 background-color: #F3DC4C