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)
25 selectedPiece: null, //moving piece (or clicked piece)
26 start: null, //pixels coordinates + id of starting square (click or drag)
28 movingArrow: { x: -1, y: -1 },
29 arrows: [], //object of {start: x,y / end: x,y}
30 circles: {}, //object of squares' ID --> true (TODO: use a set?)
33 settings: store.state.settings
38 // Return empty div of class 'game' to avoid error when setting size
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 const lm = this.lastMove;
59 this.settings.highlight &&
60 ["all","highlight"].includes(V.ShowMoves)
63 this.settings.highlight &&
64 ["all","highlight","byrow"].includes(V.ShowMoves)
66 const orientation = !V.CanFlip ? "w" : this.orientation;
67 // Ensure that squares colors do not change when board is flipped
68 const lightSquareMod = (sizeX + sizeY) % 2;
69 const showPiece = (x, y) => {
71 this.vr.board[x][y] != V.EMPTY &&
72 (!this.vr.enlightened || this.analyze || this.score != "*" ||
73 (!!this.userColor && this.vr.enlightened[this.userColor][x][y]))
76 const inHighlight = (x, y) => {
77 return showLight && !!lm && (
78 (lm.end.x == x && lm.end.y == y) ||
79 (lm.start.x == x && lm.start.y == y));
81 const inShadow = (x, y) => {
85 this.vr.enlightened &&
86 (!this.userColor || !this.vr.enlightened[this.userColor][x][y])
89 // Create board element (+ reserves if needed by variant)
90 let elementArray = [];
99 [...Array(sizeX).keys()].map(i => {
100 const ci = orientation == "w" ? i : sizeX - i - 1;
107 style: { opacity: this.choices.length > 0 ? "0.5" : "1" }
109 [...Array(sizeY).keys()].map(j => {
110 const cj = orientation == "w" ? j : sizeY - j - 1;
111 const squareId = "sq-" + ci + "-" + cj;
113 if (showPiece(ci, cj)) {
119 !!this.selectedPiece &&
120 this.selectedPiece.parentNode.id == squareId
126 this.vr.board[ci][cj],
127 // Extra args useful for some variants:
136 if (this.settings.hints && hintSquares[ci][cj]) {
143 src: "/images/mark.svg"
148 if (!!this.circles[squareId]) {
152 "circle-square": true
155 src: "/images/circle.svg"
160 const lightSquare = (ci + cj) % 2 == lightSquareMod;
166 ["board" + sizeY]: true,
167 "light-square": lightSquare,
168 "dark-square": !lightSquare,
169 [this.settings.bcolor]: true,
170 "in-shadow": inShadow(ci, cj),
171 "highlight-light": inHighlight(ci, cj) && lightSquare,
172 "highlight-dark": inHighlight(ci, cj) && !lightSquare,
174 showCheck && lightSquare && incheckSq[ci][cj],
176 showCheck && !lightSquare && incheckSq[ci][cj]
179 id: getSquareId({ x: ci, y: cj })
188 if (!!this.vr.reserve) {
189 const playingColor = this.userColor || "w"; //default for an observer
190 const shiftIdx = playingColor == "w" ? 0 : 1;
191 let myReservePiecesArray = [];
192 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
193 const qty = this.vr.reserve[playingColor][V.RESERVE_PIECES[i]];
194 myReservePiecesArray.push(
198 "class": { board: true, ["board" + sizeY]: true },
199 attrs: { id: getSquareId({ x: sizeX + shiftIdx, y: i }) },
200 style: { opacity: qty > 0 ? 1 : 0.35 }
204 "class": { piece: true, reserve: true },
208 this.vr.getReservePpath(i, playingColor) +
212 h("sup", { "class": { "reserve-count": true } }, [ qty ])
217 let oppReservePiecesArray = [];
218 const oppCol = V.GetOppCol(playingColor);
219 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
220 const qty = this.vr.reserve[oppCol][V.RESERVE_PIECES[i]];
221 oppReservePiecesArray.push(
225 "class": { board: true, ["board" + sizeY]: true },
226 attrs: { id: getSquareId({ x: sizeX + (1 - shiftIdx), y: i }) },
227 style: { opacity: qty > 0 ? 1 : 0.35 }
231 "class": { piece: true, reserve: true },
235 this.vr.getReservePpath(i, oppCol) +
239 h("sup", { "class": { "reserve-count": true } }, [ qty ])
244 const myReserveTop = (
245 (playingColor == 'w' && orientation == 'b') ||
246 (playingColor == 'b' && orientation == 'w')
248 // Center reserves, assuming same number of pieces for each side:
249 const nbReservePieces = myReservePiecesArray.length;
250 const marginLeft = ((100 - nbReservePieces * (100 / sizeY)) / 2) + "%";
260 "margin-left": marginLeft
272 myReserveTop ? myReservePiecesArray : oppReservePiecesArray
285 "margin-left": marginLeft
297 myReserveTop ? oppReservePiecesArray : myReservePiecesArray
301 elementArray.push(reserveTop);
303 elementArray.push(gameDiv);
304 if (!!this.vr.reserve) elementArray.push(reserveBottom);
305 const boardElt = document.querySelector(".game");
306 // boardElt might be undefine (at first drawing),
307 // but it won't be used in this case.
308 const squareWidth = (!!boardElt ? boardElt.offsetWidth / sizeY : 42);
309 if (this.choices.length > 0 && !!boardElt) {
310 // No choices to show at first drawing
311 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
312 const maxNbeltsPerRow = Math.min(this.choices.length, sizeY);
313 let topOffset = offset[0] + (sizeY / 2) * squareWidth - squareWidth / 2;
314 let choicesHeight = squareWidth;
315 if (this.choices.length >= sizeY) {
316 // A second row is required (Eightpieces variant)
317 topOffset -= squareWidth / 2;
323 attrs: { id: "choices" },
324 "class": { row: true },
326 top: topOffset + "px",
329 (squareWidth * Math.max(sizeY - this.choices.length, 0)) / 2 +
331 width: (maxNbeltsPerRow * squareWidth) + "px",
332 height: choicesHeight + "px"
338 "class": { "full-width": true }
340 this.choices.map(m => {
341 // A "choice" is a move
342 const applyMove = (e) => {
344 // Force a delay between move is shown and clicked
345 // (otherwise a "double-click" bug might occur)
346 if (Date.now() - this.clickTime < 200) return;
352 ? { touchend: applyMove }
353 : { mouseup: applyMove };
359 ["board" + sizeY]: true
362 width: (100 / maxNbeltsPerRow) + "%",
363 "padding-bottom": (100 / maxNbeltsPerRow) + "%"
371 // orientation: extra arg useful for some variants:
372 this.vr.getPPpath(m, this.orientation) +
375 "class": { "choice-piece": true },
383 elementArray.unshift(choices);
386 !this.mobileBrowser &&
387 (this.arrows.length > 0 || this.movingArrow.x >= 0)
390 const arrowWidth = squareWidth / 4;
391 this.arrows.forEach(a => {
392 const endPoint = this.adjustEndArrow(a.start, a.end, squareWidth);
397 "class": { "svg-arrow": true },
400 "M" + a.start.x + "," + a.start.y + " " +
401 "L" + endPoint.x + "," + endPoint.y
403 style: "stroke-width:" + arrowWidth + "px"
409 if (this.movingArrow.x >= 0) {
411 this.adjustEndArrow(this.startArrow, this.movingArrow, squareWidth);
416 "class": { "svg-arrow": true },
419 "M" + this.startArrow.x + "," + this.startArrow.y + " " +
420 "L" + endPoint.x + "," + endPoint.y
422 style: "stroke-width:" + arrowWidth + "px"
428 // Add SVG element for drawing arrows
448 markerWidth: (2 * arrowWidth) + "px",
449 markerHeight: (3 * arrowWidth) + "px",
450 markerUnits: "userSpaceOnUse",
452 refY: (1.5 * arrowWidth) + "px",
460 "class": { "arrow-head": true },
463 "M0,0 L0," + (3 * arrowWidth) + " L" +
464 (2 * arrowWidth) + "," + (1.5 * arrowWidth) + " z"
478 // NOTE: click = mousedown + mouseup
479 if (this.mobileBrowser) {
482 touchstart: this.mousedown,
483 touchmove: this.mousemove,
484 touchend: this.mouseup
490 mousedown: this.mousedown,
491 mousemove: this.mousemove,
492 mouseup: this.mouseup,
493 contextmenu: this.blockContextMenu
497 return h("div", onEvents, elementArray);
500 blockContextMenu: function(e) {
505 cancelResetArrows: function() {
506 this.startArrow = null;
510 adjustEndArrow: function(start, end, squareWidth) {
511 // Simple heuristic for now, just remove 1/3 square.
512 // TODO: should depend on the orientation.
513 const delta = [end.x - start.x, end.y - start.y];
514 const dist = Math.sqrt(delta[0] * delta[0] + delta[1] * delta[1]);
515 const fracSqWidth = squareWidth / 3;
517 x: end.x - delta[0] * fracSqWidth / dist,
518 y: end.y - delta[1] * fracSqWidth / dist
521 mousedown: function(e) {
523 if (!this.mobileBrowser && e.which != 3)
524 // Cancel current drawing and circles, if any
525 this.cancelResetArrows();
526 if (this.mobileBrowser || e.which == 1) {
529 // NOTE: classList[0] is enough: 'piece' is the first assigned class
530 const withPiece = (e.target.classList[0] == "piece");
531 // Emit the click event which could be used by some variants
534 getSquareFromId(withPiece ? e.target.parentNode.id : e.target.id)
536 // Start square must contain a piece.
537 if (!withPiece) return;
538 let parent = e.target.parentNode; //surrounding square
539 // Show possible moves if current player allowed to play
540 const startSquare = getSquareFromId(parent.id);
541 this.possibleMoves = [];
542 const color = this.analyze ? this.vr.turn : this.userColor;
543 if (this.vr.canIplay(color, startSquare))
544 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
545 // For potential drag'n drop, remember start coordinates
546 // (to center the piece on mouse cursor)
547 const rect = parent.getBoundingClientRect();
549 x: rect.x + rect.width / 2,
550 y: rect.y + rect.width / 2,
553 // Add the moving piece to the board, just after current image
554 this.selectedPiece = e.target.cloneNode();
556 this.selectedPiece.style,
558 position: "absolute",
560 display: "inline-block",
564 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
566 this.processMoveAttempt(e);
568 } else if (e.which == 3) {
569 // Mouse right button
571 // Next loop because of potential marks
572 while (elem.tagName == "IMG") elem = elem.parentNode;
573 // To center the arrow in square:
574 const rect = elem.getBoundingClientRect();
576 x: rect.x + rect.width / 2,
577 y: rect.y + rect.width / 2,
582 mousemove: function(e) {
583 if (!this.selectedPiece && !this.startArrow) return;
585 if (!!this.selectedPiece) {
586 // There is an active element: move it around
587 const [offsetX, offsetY] =
589 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
590 : [e.clientX, e.clientY];
592 this.selectedPiece.style,
594 left: offsetX - this.start.x + "px",
595 top: offsetY - this.start.y + "px"
601 // Next loop because of potential marks
602 while (elem.tagName == "IMG") elem = elem.parentNode;
603 // To center the arrow in square:
604 if (elem.id != this.startArrow.id) {
605 const rect = elem.getBoundingClientRect();
607 x: rect.x + rect.width / 2,
608 y: rect.y + rect.width / 2
613 mouseup: function(e) {
615 if (this.mobileBrowser || e.which == 1) {
616 if (!this.selectedPiece) return;
617 // Drag'n drop. Selected piece is no longer needed:
618 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
619 delete this.selectedPiece;
620 this.selectedPiece = null;
621 this.processMoveAttempt(e);
622 } else if (e.which == 3) {
623 // Mouse right button
624 this.movingArrow = { x: -1, y: -1 };
625 this.processArrowAttempt(e);
628 // Called by BaseGame after partially undoing multi-moves:
629 resetCurrentAttempt: function() {
630 this.possibleMoves = [];
633 this.selectedPiece = null;
635 processMoveAttempt: function(e) {
636 // Obtain the move from start and end squares
637 const [offsetX, offsetY] =
639 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
640 : [e.clientX, e.clientY];
641 let landing = document.elementFromPoint(offsetX, offsetY);
642 // Next condition: classList.contains(piece) fails because of marks
643 while (landing.tagName == "IMG") landing = landing.parentNode;
644 if (this.start.id == landing.id) {
645 if (this.click == landing.id) {
646 // Second click on same square: cancel current move
647 this.possibleMoves = [];
650 } else this.click = landing.id;
654 // OK: process move attempt, landing is a square node
655 let endSquare = getSquareFromId(landing.id);
656 let moves = this.findMatchingMoves(endSquare);
657 this.possibleMoves = [];
658 if (moves.length > 1) {
659 this.clickTime = Date.now();
660 this.choices = moves;
661 } else if (moves.length == 1) this.play(moves[0]);
662 // else: forbidden move attempt
664 processArrowAttempt: function(e) {
665 // Obtain the arrow from start and end squares
666 const [offsetX, offsetY] = [e.clientX, e.clientY];
667 let landing = document.elementFromPoint(offsetX, offsetY);
668 // Next condition: classList.contains(piece) fails because of marks
669 while (landing.tagName == "IMG") landing = landing.parentNode;
670 if (this.startArrow.id == landing.id)
671 // Draw (or erase) a circle
672 this.$set(this.circles, landing.id, !this.circles[landing.id]);
674 // OK: add arrow, landing is a new square
675 const rect = landing.getBoundingClientRect();
678 x: this.startArrow.x,
682 x: rect.x + rect.width / 2,
683 y: rect.y + rect.width / 2
687 this.startArrow = null;
689 findMatchingMoves: function(endSquare) {
690 // Run through moves list and return the matching set (if promotions...)
692 this.possibleMoves.filter(m => {
693 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
697 play: function(move) {
698 this.$emit("play-move", move);
704 <style lang="sass" scoped>
705 // NOTE: no variants with reserve of size != 8
729 background-color: rgba(0,0,0,0)
732 background-color: #e6ee9c
734 background-color: skyblue
757 marker-end: url(#arrow)
763 background-color: rgba(204, 51, 0, 0.7) !important
765 background-color: rgba(204, 51, 0, 0.9) !important
767 .light-square.lichess
768 background-color: #f0d9b5;
770 background-color: #b58863;
772 .light-square.chesscom
773 background-color: #e5e5ca;
774 .dark-square.chesscom
775 background-color: #6f8f57;
777 .light-square.chesstempo
778 background-color: #dfdfdf;
779 .dark-square.chesstempo
780 background-color: #7287b6;
782 // TODO: no predefined highlight colors, but layers. How?
784 .light-square.lichess.highlight-light
785 background-color: #cdd26a
786 .dark-square.lichess.highlight-dark
787 background-color: #aaa23a
789 .light-square.chesscom.highlight-light
790 background-color: #f7f783
791 .dark-square.chesscom.highlight-dark
792 background-color: #bacb44
794 .light-square.chesstempo.highlight-light
795 background-color: #9f9fff
796 .dark-square.chesstempo.highlight-dark
797 background-color: #557fff