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],
198 this.vr.hoverHighlight(
199 [ci, cj], !this.analyze ? this.userColor : null)
202 id: getSquareId({ x: ci, y: cj })
211 if (!!this.vr.reserve) {
212 const playingColor = this.userColor || "w"; //default for an observer
213 const shiftIdx = playingColor == "w" ? 0 : 1;
214 // Some variants have more than sizeY reserve pieces (Clorange: 10)
215 const reserveSquareNb = Math.max(sizeY, V.RESERVE_PIECES.length);
216 let myReservePiecesArray = [];
217 if (!!this.vr.reserve[playingColor]) {
218 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
219 const qty = this.vr.reserve[playingColor][V.RESERVE_PIECES[i]];
220 myReservePiecesArray.push(
224 "class": { board: true, ["board" + reserveSquareNb]: true },
225 attrs: { id: getSquareId({ x: sizeX + shiftIdx, y: i }) },
226 style: { opacity: qty > 0 ? 1 : 0.35 }
230 // NOTE: class "reserve" not used currently
231 "class": { piece: true, reserve: true },
235 this.vr.getReservePpath(i, playingColor, orientation) +
242 "class": { "reserve-count": true },
243 style: { top: "calc(100% + 5px)" }
252 let oppReservePiecesArray = [];
253 const oppCol = V.GetOppCol(playingColor);
254 if (!!this.vr.reserve[oppCol]) {
255 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
256 const qty = this.vr.reserve[oppCol][V.RESERVE_PIECES[i]];
257 oppReservePiecesArray.push(
261 "class": { board: true, ["board" + reserveSquareNb]: true },
262 attrs: { id: getSquareId({ x: sizeX + (1 - shiftIdx), y: i }) },
263 style: { opacity: qty > 0 ? 1 : 0.35 }
267 "class": { piece: true, reserve: true },
271 this.vr.getReservePpath(i, oppCol, orientation) +
278 "class": { "reserve-count": true },
279 style: { top: "calc(100% + 5px)" }
288 const myReserveTop = (
289 (playingColor == 'w' && orientation == 'b') ||
290 (playingColor == 'b' && orientation == 'w')
292 const hasReserveTop = (
293 (myReserveTop && !!this.vr.reserve[playingColor]) ||
294 (!myReserveTop && !!this.vr.reserve[oppCol])
296 // "var" because must be reachable from outside this block
297 var hasReserveBottom = (
298 (myReserveTop && !!this.vr.reserve[oppCol]) ||
299 (!myReserveTop && !!this.vr.reserve[playingColor])
301 // Center reserves, assuming same number of pieces for each side:
302 const nbReservePieces = myReservePiecesArray.length;
304 ((100 - nbReservePieces * (100 / reserveSquareNb)) / 2) + "%";
315 "margin-left": marginLeft
327 myReserveTop ? myReservePiecesArray : oppReservePiecesArray
332 if (hasReserveBottom) {
342 "margin-left": marginLeft
354 myReserveTop ? oppReservePiecesArray : myReservePiecesArray
359 if (hasReserveTop) elementArray.push(reserveTop);
361 elementArray.push(gameDiv);
362 if (!!this.vr.reserve && hasReserveBottom)
363 elementArray.push(reserveBottom);
364 const boardElt = document.getElementById("gamePosition");
365 // boardElt might be undefine (at first drawing)
366 if (this.choices.length > 0 && !!boardElt) {
367 const squareWidth = boardElt.offsetWidth / sizeY;
368 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
369 const maxNbeltsPerRow = Math.min(this.choices.length, sizeY);
370 let topOffset = offset[0] + ((sizeX - 1) / 2) * squareWidth;
371 let choicesHeight = squareWidth;
372 if (this.choices.length >= sizeY) {
373 // A second row is required (Eightpieces variant)
374 topOffset -= squareWidth / 2;
380 attrs: { id: "choices" },
381 "class": { row: true },
383 top: topOffset + "px",
386 (squareWidth * Math.max(sizeY - this.choices.length, 0)) / 2 +
388 width: (maxNbeltsPerRow * squareWidth) + "px",
389 height: choicesHeight + "px"
395 "class": { "full-width": true }
397 this.choices.map(m => {
398 // A "choice" is a move
399 const applyMove = (e) => {
401 // Force a delay between move is shown and clicked
402 // (otherwise a "double-click" bug might occur)
403 if (Date.now() - this.clickTime < 200) return;
407 const stopPropagation = (e) => { e.stopPropagation(); }
410 // Must cancel mousedown logic:
411 ? { touchstart: stopPropagation, touchend: applyMove }
412 : { mousedown: stopPropagation, mouseup: applyMove };
418 ["board" + sizeY]: true
421 width: (100 / maxNbeltsPerRow) + "%",
422 "padding-bottom": (100 / maxNbeltsPerRow) + "%"
430 // orientation: extra arg useful for some variants
431 this.vr.getPPpath(m, this.orientation) +
434 "class": { "choice-piece": true },
442 elementArray.unshift(choices);
445 // NOTE: click = mousedown + mouseup
446 if (this.mobileBrowser) {
449 touchstart: this.mousedown,
450 touchmove: this.mousemove,
451 touchend: this.mouseup
458 mousedown: this.mousedown,
459 mousemove: this.mousemove,
460 mouseup: this.mouseup,
461 contextmenu: this.blockContextMenu
468 Object.assign({ attrs: { id: "rootBoardElement" } }, onEvents),
473 updated: function() {
474 this.re_setDrawings();
477 blockContextMenu: function(e) {
482 cancelResetArrows: function() {
483 this.startArrow = null;
486 const curCanvas = document.getElementById("arrowCanvas");
487 if (!!curCanvas) curCanvas.parentNode.removeChild(curCanvas);
489 coordsToXY: function(coords, top, left, squareWidth) {
491 // [1] for x and [0] for y because conventions in rules are inversed.
493 left + window.scrollX +
496 (this.orientation == 'w' ? coords[1] : (V.size.y - coords[1]))
500 top + window.scrollY +
503 (this.orientation == 'w' ? coords[0] : (V.size.x - coords[0]))
508 computeEndArrow: function(start, end, top, left, squareWidth) {
509 const endCoords = this.coordsToXY(end, top, left, squareWidth);
510 const delta = [endCoords.x - start.x, endCoords.y - start.y];
511 const dist = Math.sqrt(delta[0] * delta[0] + delta[1] * delta[1]);
512 // Simple heuristic for now, just remove 1/3 square.
513 // TODO: should depend on the orientation.
514 const fracSqWidth = squareWidth / 3;
516 x: endCoords.x - delta[0] * fracSqWidth / dist,
517 y: endCoords.y - delta[1] * fracSqWidth / dist
520 drawCurrentArrow: function() {
521 const boardElt = document.getElementById("gamePosition");
522 const squareWidth = boardElt.offsetWidth / V.size.y;
523 const bPos = boardElt.getBoundingClientRect();
526 [this.startArrow[0] + 0.5, this.startArrow[1] + 0.5],
527 bPos.top, bPos.left, squareWidth);
529 this.computeEndArrow(
530 aStart, [this.movingArrow[0] + 0.5, this.movingArrow[1] + 0.5],
531 bPos.top, bPos.left, squareWidth);
532 let currentArrow = document.getElementById("currentArrow");
534 "M" + aStart.x + "," + aStart.y + " " + "L" + aEnd.x + "," + aEnd.y;
535 const arrowWidth = squareWidth / 4;
536 if (!!currentArrow) currentArrow.setAttribute("d", d);
539 document.createElementNS("http://www.w3.org/2000/svg", "path");
540 domArrow.classList.add("svg-arrow");
541 domArrow.id = "currentArrow";
542 domArrow.setAttribute("d", d);
543 domArrow.style = "stroke-width:" + arrowWidth + "px";
544 document.getElementById("arrowCanvas")
545 .insertAdjacentElement("beforeend", domArrow);
548 addArrow: function(arrow) {
549 const arrowIdx = this.arrows.findIndex(a => {
551 a.start[0] == arrow.start[0] && a.start[1] == arrow.start[1] &&
552 a.end[0] == arrow.end[0] && a.end[1] == arrow.end[1]
557 this.arrows.splice(arrowIdx, 1);
559 // Add to arrows vector:
560 this.arrows.push(arrow);
561 // NOTE: no need to draw here, will be re-draw
562 // by updated() hook callong re_setDrawings()
564 getSvgArrow: function(arrow, top, left, squareWidth) {
567 [arrow.start[0] + 0.5, arrow.start[1] + 0.5],
568 top, left, squareWidth);
570 this.computeEndArrow(
571 aStart, [arrow.end[0] + 0.5, arrow.end[1] + 0.5],
572 top, left, squareWidth);
573 const arrowWidth = squareWidth / 4;
575 document.createElementNS("http://www.w3.org/2000/svg", "path");
576 path.classList.add("svg-arrow");
579 "M" + aStart.x + "," + aStart.y + " " + "L" + aEnd.x + "," + aEnd.y
581 path.style = "stroke-width:" + arrowWidth + "px";
584 re_setDrawings: function() {
585 // Add some drawing on board (for some variants + arrows and circles)
586 const boardElt = document.getElementById("gamePosition");
587 if (!boardElt) return;
588 // Remove current canvas, if any
589 const curCanvas = document.getElementById("arrowCanvas");
590 if (!!curCanvas) curCanvas.parentNode.removeChild(curCanvas);
591 const squareWidth = boardElt.offsetWidth / V.size.y;
592 const bPos = boardElt.getBoundingClientRect();
594 this.arrows.forEach(a => {
595 svgArrows.push(this.getSvgArrow(a, bPos.top, bPos.left, squareWidth));
599 V.Lines.forEach(line => {
601 this.coordsToXY(line[0], bPos.top, bPos.left, squareWidth);
603 this.coordsToXY(line[1], bPos.top, bPos.left, squareWidth);
605 document.createElementNS("http://www.w3.org/2000/svg", "path");
606 if (line[0][0] == line[1][0] || line[0][1] == line[1][1])
607 path.classList.add("svg-line");
609 // "Diagonals" are drawn with a lighter color (TODO: generalize)
610 path.classList.add("svg-diag");
613 "M" + lStart.x + "," + lStart.y + " " +
614 "L" + lEnd.x + "," + lEnd.y
620 document.createElementNS("http://www.w3.org/2000/svg", "svg");
621 arrowCanvas.id = "arrowCanvas";
622 arrowCanvas.setAttribute("stroke", "none");
624 document.createElementNS("http://www.w3.org/2000/svg", "defs");
625 const arrowWidth = squareWidth / 4;
627 document.createElementNS("http://www.w3.org/2000/svg", "marker");
629 marker.setAttribute("markerWidth", (2 * arrowWidth) + "px");
630 marker.setAttribute("markerHeight", (3 * arrowWidth) + "px");
631 marker.setAttribute("markerUnits", "userSpaceOnUse");
632 marker.setAttribute("refX", "0");
633 marker.setAttribute("refY", (1.5 * arrowWidth) + "px");
634 marker.setAttribute("orient", "auto");
636 document.createElementNS("http://www.w3.org/2000/svg", "path");
637 head.classList.add("arrow-head");
640 "M0,0 L0," + (3 * arrowWidth) + " L" +
641 (2 * arrowWidth) + "," + (1.5 * arrowWidth) + " z"
643 marker.appendChild(head);
644 defs.appendChild(marker);
645 arrowCanvas.appendChild(defs);
646 svgArrows.concat(vLines).forEach(av => arrowCanvas.appendChild(av));
647 document.getElementById("rootBoardElement").appendChild(arrowCanvas);
649 mousedown: function(e) {
651 if (!this.mobileBrowser && e.which != 3)
652 // Cancel current drawing and circles, if any
653 this.cancelResetArrows();
654 if (this.mobileBrowser || e.which == 1) {
658 document.getElementById("boardContainer").getBoundingClientRect();
659 // NOTE: classList[0] is enough: 'piece' is the first assigned class
660 const withPiece = (e.target.classList[0] == "piece");
661 // Show possible moves if current player allowed to play
663 getSquareFromId(withPiece ? e.target.parentNode.id : e.target.id);
664 this.possibleMoves = [];
665 const color = this.analyze ? this.vr.turn : this.userColor;
666 if (this.vr.canIplay(color, startSquare)) {
667 // Emit the click event which could be used by some variants
669 (withPiece ? e.target.parentNode.id : e.target.id);
670 const sq = getSquareFromId(targetId);
671 this.$emit("click-square", sq);
672 if (withPiece && !this.vr.onlyClick(sq)) {
673 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
674 if (this.possibleMoves.length > 0) {
675 // For potential drag'n drop, remember start coordinates
676 // (to center the piece on mouse cursor)
677 let parent = e.target.parentNode; //surrounding square
678 const rect = parent.getBoundingClientRect();
680 x: rect.x + rect.width / 2,
681 y: rect.y + rect.width / 2,
684 // Add the moving piece to the board, just after current image
685 this.selectedPiece = e.target.cloneNode();
687 this.selectedPiece.style,
689 position: "absolute",
691 display: "inline-block",
695 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
700 else this.processMoveAttempt(e);
702 else if (e.which == 3) {
703 // Mouse right button
705 document.getElementById("gamePosition").getBoundingClientRect();
707 // Next loop because of potential marks
708 while (elem.tagName == "IMG") elem = elem.parentNode;
709 this.startArrow = getSquareFromId(elem.id);
712 mousemove: function(e) {
713 if (!this.selectedPiece && !this.startArrow) return;
714 // Cancel if off boardContainer
715 const [offsetX, offsetY] =
717 ? [e.changedTouches[0].clientX, e.changedTouches[0].clientY]
718 : [e.clientX, e.clientY];
720 offsetX < this.containerPos.left ||
721 offsetX > this.containerPos.right ||
722 offsetY < this.containerPos.top ||
723 offsetY > this.containerPos.bottom
725 if (!!this.selectedPiece) {
726 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
727 delete this.selectedPiece;
728 this.selectedPiece = null;
730 this.possibleMoves = []; //in case of
732 let selected = document.querySelector(".ghost");
733 if (!!selected) selected.classList.remove("ghost");
736 this.startArrow = null;
737 this.movingArrow = null;
738 const currentArrow = document.getElementById("currentArrow");
740 currentArrow.parentNode.removeChild(currentArrow);
745 if (!!this.selectedPiece) {
746 // There is an active element: move it around
748 this.selectedPiece.style,
750 left: offsetX - this.start.x + "px",
751 top: offsetY - this.start.y + "px"
757 // Next loop because of potential marks
758 while (elem.tagName == "IMG") elem = elem.parentNode;
759 // To center the arrow in square:
760 const movingCoords = getSquareFromId(elem.id);
762 movingCoords[0] != this.startArrow[0] ||
763 movingCoords[1] != this.startArrow[1]
765 this.movingArrow = movingCoords;
766 this.drawCurrentArrow();
770 mouseup: function(e) {
772 if (this.mobileBrowser || e.which == 1) {
773 if (!this.selectedPiece) return;
774 // Drag'n drop. Selected piece is no longer needed:
775 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
776 delete this.selectedPiece;
777 this.selectedPiece = null;
778 this.processMoveAttempt(e);
779 } else if (e.which == 3) {
780 if (!this.startArrow) return;
781 // Mouse right button
782 this.movingArrow = null;
783 this.processArrowAttempt(e);
786 // Called by BaseGame after partially undoing multi-moves:
787 resetCurrentAttempt: function() {
788 this.possibleMoves = [];
791 this.selectedPiece = null;
793 processMoveAttempt: function(e) {
794 // Obtain the move from start and end squares
795 const [offsetX, offsetY] =
797 ? [e.changedTouches[0].clientX, e.changedTouches[0].clientY]
798 : [e.clientX, e.clientY];
799 let landing = document.elementFromPoint(offsetX, offsetY);
800 // Next condition: classList.contains(piece) fails because of marks
801 while (landing.tagName == "IMG") landing = landing.parentNode;
802 if (this.start.id == landing.id) {
803 if (this.click == landing.id) {
804 // Second click on same square: cancel current move
805 this.possibleMoves = [];
808 } else this.click = landing.id;
812 // OK: process move attempt, landing is a square node
813 let endSquare = getSquareFromId(landing.id);
814 let moves = this.findMatchingMoves(endSquare);
815 this.possibleMoves = [];
816 if (moves.length > 1) {
817 this.clickTime = Date.now();
818 this.choices = moves;
819 } else if (moves.length == 1) this.play(moves[0]);
820 // else: forbidden move attempt
822 processArrowAttempt: function(e) {
823 // Obtain the arrow from start and end squares
824 const [offsetX, offsetY] = [e.clientX, e.clientY];
825 let landing = document.elementFromPoint(offsetX, offsetY);
826 // Next condition: classList.contains(piece) fails because of marks
827 while (landing.tagName == "IMG") landing = landing.parentNode;
828 const landingCoords = getSquareFromId(landing.id);
830 this.startArrow[0] == landingCoords[0] &&
831 this.startArrow[1] == landingCoords[1]
833 // Draw (or erase) a circle
834 this.$set(this.circles, landing.id, !this.circles[landing.id]);
837 // OK: add arrow, landing is a new square
838 const currentArrow = document.getElementById("currentArrow");
839 currentArrow.parentNode.removeChild(currentArrow);
841 start: this.startArrow,
845 this.startArrow = null;
847 findMatchingMoves: function(endSquare) {
848 // Run through moves list and return the matching set (if promotions...)
850 this.possibleMoves.filter(m => {
851 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
855 play: function(move) {
856 this.$emit("play-move", move);
863 // SVG dynamically added, so not scoped
876 marker-end: url(#arrow)
888 <style lang="sass" scoped>
889 @import "@/styles/_board_squares_img.sass";
892 // TODO: would be cleaner to restrict width so that it doesn't overflow
893 // Commented out because pieces would disappear over the board otherwise:
898 display: inline-block
919 background-color: rgba(0,0,0,0)
922 background-color: #e6ee9c
924 background-color: skyblue
931 // NOTE: no need to set z-index here, since opacity is low
937 background-color: rgba(204, 51, 0, 0.7) !important
939 background-color: rgba(204, 51, 0, 0.9) !important
941 // TODO: no predefined highlight colors, but layers. How?
943 .hover-highlight:hover
944 // TODO: color dependant on board theme, or inner border...
945 background-color: #C571E6 !important
950 background-color: #cdd26a
952 background-color: #f7f783
954 background-color: #9f9fff
956 background-color: #fef273
959 background-color: #aaa23a
961 background-color: #bacb44
963 background-color: #557fff
965 background-color: #e8c525
968 background-color: #BCBA52
970 background-color: #D9E164
972 background-color: #7A8FFF
974 background-color: #F3DC4C