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 let lm = this.lastMove;
58 // Precompute lastMove highlighting squares
59 const lmHighlights = {};
61 if (!Array.isArray(lm)) lm = [lm];
63 lmHighlights[m.start.x + sizeX * m.start.y] = true;
64 lmHighlights[m.end.x + sizeX * m.end.y] = true;
68 this.settings.highlight &&
69 ["all","highlight"].includes(V.ShowMoves)
72 this.settings.highlight &&
73 ["all","highlight","byrow"].includes(V.ShowMoves)
75 const orientation = !V.CanFlip ? "w" : this.orientation;
76 // Ensure that squares colors do not change when board is flipped
77 const lightSquareMod = (sizeX + sizeY) % 2;
78 const showPiece = (x, y) => {
80 this.vr.board[x][y] != V.EMPTY &&
81 (!this.vr.enlightened || this.analyze || this.score != "*" ||
82 (!!this.userColor && this.vr.enlightened[this.userColor][x][y]))
85 const inHighlight = (x, y) => {
86 return showLight && !!lmHighlights[x + sizeX * y];
88 const inShadow = (x, y) => {
92 this.vr.enlightened &&
93 (!this.userColor || !this.vr.enlightened[this.userColor][x][y])
96 // Create board element (+ reserves if needed by variant)
97 let elementArray = [];
106 [...Array(sizeX).keys()].map(i => {
107 const ci = orientation == "w" ? i : sizeX - i - 1;
114 style: { opacity: this.choices.length > 0 ? "0.5" : "1" }
116 [...Array(sizeY).keys()].map(j => {
117 const cj = orientation == "w" ? j : sizeY - j - 1;
118 const squareId = "sq-" + ci + "-" + cj;
120 if (showPiece(ci, cj)) {
126 !!this.selectedPiece &&
127 this.selectedPiece.parentNode.id == squareId
133 this.vr.board[ci][cj],
134 // Extra args useful for some variants:
143 if (this.settings.hints && hintSquares[ci][cj]) {
150 src: "/images/mark.svg"
155 if (!!this.circles[squareId]) {
159 "circle-square": true
162 src: "/images/circle.svg"
167 const lightSquare = (ci + cj) % 2 == lightSquareMod;
173 ["board" + sizeY]: true,
174 "light-square": lightSquare,
175 "dark-square": !lightSquare,
176 [this.settings.bcolor]: true,
177 "in-shadow": inShadow(ci, cj),
178 "highlight-light": inHighlight(ci, cj) && lightSquare,
179 "highlight-dark": inHighlight(ci, cj) && !lightSquare,
181 showCheck && lightSquare && incheckSq[ci][cj],
183 showCheck && !lightSquare && incheckSq[ci][cj]
186 id: getSquareId({ x: ci, y: cj })
195 if (!!this.vr.reserve) {
196 const playingColor = this.userColor || "w"; //default for an observer
197 const shiftIdx = playingColor == "w" ? 0 : 1;
198 let myReservePiecesArray = [];
199 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
200 const qty = this.vr.reserve[playingColor][V.RESERVE_PIECES[i]];
201 myReservePiecesArray.push(
205 "class": { board: true, ["board" + sizeY]: true },
206 attrs: { id: getSquareId({ x: sizeX + shiftIdx, y: i }) },
207 style: { opacity: qty > 0 ? 1 : 0.35 }
211 "class": { piece: true, reserve: true },
215 this.vr.getReservePpath(i, playingColor) +
219 h("sup", { "class": { "reserve-count": true } }, [ qty ])
224 let oppReservePiecesArray = [];
225 const oppCol = V.GetOppCol(playingColor);
226 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
227 const qty = this.vr.reserve[oppCol][V.RESERVE_PIECES[i]];
228 oppReservePiecesArray.push(
232 "class": { board: true, ["board" + sizeY]: true },
233 attrs: { id: getSquareId({ x: sizeX + (1 - shiftIdx), y: i }) },
234 style: { opacity: qty > 0 ? 1 : 0.35 }
238 "class": { piece: true, reserve: true },
242 this.vr.getReservePpath(i, oppCol) +
246 h("sup", { "class": { "reserve-count": true } }, [ qty ])
251 const myReserveTop = (
252 (playingColor == 'w' && orientation == 'b') ||
253 (playingColor == 'b' && orientation == 'w')
255 // Center reserves, assuming same number of pieces for each side:
256 const nbReservePieces = myReservePiecesArray.length;
257 const marginLeft = ((100 - nbReservePieces * (100 / sizeY)) / 2) + "%";
267 "margin-left": marginLeft
279 myReserveTop ? myReservePiecesArray : oppReservePiecesArray
292 "margin-left": marginLeft
304 myReserveTop ? oppReservePiecesArray : myReservePiecesArray
308 elementArray.push(reserveTop);
310 elementArray.push(gameDiv);
311 if (!!this.vr.reserve) elementArray.push(reserveBottom);
312 const boardElt = document.querySelector(".game");
313 // boardElt might be undefine (at first drawing),
314 // but it won't be used in this case.
315 const squareWidth = (!!boardElt ? boardElt.offsetWidth / sizeY : 42);
316 if (this.choices.length > 0 && !!boardElt) {
317 // No choices to show at first drawing
318 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
319 const maxNbeltsPerRow = Math.min(this.choices.length, sizeY);
320 let topOffset = offset[0] + (sizeY / 2) * squareWidth - squareWidth / 2;
321 let choicesHeight = squareWidth;
322 if (this.choices.length >= sizeY) {
323 // A second row is required (Eightpieces variant)
324 topOffset -= squareWidth / 2;
330 attrs: { id: "choices" },
331 "class": { row: true },
333 top: topOffset + "px",
336 (squareWidth * Math.max(sizeY - this.choices.length, 0)) / 2 +
338 width: (maxNbeltsPerRow * squareWidth) + "px",
339 height: choicesHeight + "px"
345 "class": { "full-width": true }
347 this.choices.map(m => {
348 // A "choice" is a move
349 const applyMove = (e) => {
351 // Force a delay between move is shown and clicked
352 // (otherwise a "double-click" bug might occur)
353 if (Date.now() - this.clickTime < 200) return;
359 ? { touchend: applyMove }
360 : { mouseup: applyMove };
366 ["board" + sizeY]: true
369 width: (100 / maxNbeltsPerRow) + "%",
370 "padding-bottom": (100 / maxNbeltsPerRow) + "%"
378 // orientation: extra arg useful for some variants:
379 this.vr.getPPpath(m, this.orientation) +
382 "class": { "choice-piece": true },
390 elementArray.unshift(choices);
393 !this.mobileBrowser &&
394 (this.arrows.length > 0 || this.movingArrow.x >= 0)
397 const arrowWidth = squareWidth / 4;
398 this.arrows.forEach(a => {
399 const endPoint = this.adjustEndArrow(a.start, a.end, squareWidth);
404 "class": { "svg-arrow": true },
407 "M" + a.start.x + "," + a.start.y + " " +
408 "L" + endPoint.x + "," + endPoint.y
410 style: "stroke-width:" + arrowWidth + "px"
416 if (this.movingArrow.x >= 0) {
418 this.adjustEndArrow(this.startArrow, this.movingArrow, squareWidth);
423 "class": { "svg-arrow": true },
426 "M" + this.startArrow.x + "," + this.startArrow.y + " " +
427 "L" + endPoint.x + "," + endPoint.y
429 style: "stroke-width:" + arrowWidth + "px"
435 // Add SVG element for drawing arrows
455 markerWidth: (2 * arrowWidth) + "px",
456 markerHeight: (3 * arrowWidth) + "px",
457 markerUnits: "userSpaceOnUse",
459 refY: (1.5 * arrowWidth) + "px",
467 "class": { "arrow-head": true },
470 "M0,0 L0," + (3 * arrowWidth) + " L" +
471 (2 * arrowWidth) + "," + (1.5 * arrowWidth) + " z"
485 // NOTE: click = mousedown + mouseup
486 if (this.mobileBrowser) {
489 touchstart: this.mousedown,
490 touchmove: this.mousemove,
491 touchend: this.mouseup
497 mousedown: this.mousedown,
498 mousemove: this.mousemove,
499 mouseup: this.mouseup,
500 contextmenu: this.blockContextMenu
504 return h("div", onEvents, elementArray);
507 blockContextMenu: function(e) {
512 cancelResetArrows: function() {
513 this.startArrow = null;
517 adjustEndArrow: function(start, end, squareWidth) {
518 // Simple heuristic for now, just remove 1/3 square.
519 // TODO: should depend on the orientation.
520 const delta = [end.x - start.x, end.y - start.y];
521 const dist = Math.sqrt(delta[0] * delta[0] + delta[1] * delta[1]);
522 const fracSqWidth = squareWidth / 3;
524 x: end.x - delta[0] * fracSqWidth / dist,
525 y: end.y - delta[1] * fracSqWidth / dist
528 mousedown: function(e) {
530 if (!this.mobileBrowser && e.which != 3)
531 // Cancel current drawing and circles, if any
532 this.cancelResetArrows();
533 if (this.mobileBrowser || e.which == 1) {
536 // NOTE: classList[0] is enough: 'piece' is the first assigned class
537 const withPiece = (e.target.classList[0] == "piece");
538 // Emit the click event which could be used by some variants
541 getSquareFromId(withPiece ? e.target.parentNode.id : e.target.id)
543 // Start square must contain a piece.
544 if (!withPiece) return;
545 let parent = e.target.parentNode; //surrounding square
546 // Show possible moves if current player allowed to play
547 const startSquare = getSquareFromId(parent.id);
548 this.possibleMoves = [];
549 const color = this.analyze ? this.vr.turn : this.userColor;
550 if (this.vr.canIplay(color, startSquare))
551 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
552 // For potential drag'n drop, remember start coordinates
553 // (to center the piece on mouse cursor)
554 const rect = parent.getBoundingClientRect();
556 x: rect.x + rect.width / 2,
557 y: rect.y + rect.width / 2,
560 // Add the moving piece to the board, just after current image
561 this.selectedPiece = e.target.cloneNode();
563 this.selectedPiece.style,
565 position: "absolute",
567 display: "inline-block",
571 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
573 this.processMoveAttempt(e);
575 } else if (e.which == 3) {
576 // Mouse right button
578 // Next loop because of potential marks
579 while (elem.tagName == "IMG") elem = elem.parentNode;
580 // To center the arrow in square:
581 const rect = elem.getBoundingClientRect();
583 x: rect.x + rect.width / 2,
584 y: rect.y + rect.width / 2,
589 mousemove: function(e) {
590 if (!this.selectedPiece && !this.startArrow) return;
592 if (!!this.selectedPiece) {
593 // There is an active element: move it around
594 const [offsetX, offsetY] =
596 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
597 : [e.clientX, e.clientY];
599 this.selectedPiece.style,
601 left: offsetX - this.start.x + "px",
602 top: offsetY - this.start.y + "px"
608 // Next loop because of potential marks
609 while (elem.tagName == "IMG") elem = elem.parentNode;
610 // To center the arrow in square:
611 if (elem.id != this.startArrow.id) {
612 const rect = elem.getBoundingClientRect();
614 x: rect.x + rect.width / 2,
615 y: rect.y + rect.width / 2
620 mouseup: function(e) {
622 if (this.mobileBrowser || e.which == 1) {
623 if (!this.selectedPiece) return;
624 // Drag'n drop. Selected piece is no longer needed:
625 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
626 delete this.selectedPiece;
627 this.selectedPiece = null;
628 this.processMoveAttempt(e);
629 } else if (e.which == 3) {
630 // Mouse right button
631 this.movingArrow = { x: -1, y: -1 };
632 this.processArrowAttempt(e);
635 // Called by BaseGame after partially undoing multi-moves:
636 resetCurrentAttempt: function() {
637 this.possibleMoves = [];
640 this.selectedPiece = null;
642 processMoveAttempt: function(e) {
643 // Obtain the move from start and end squares
644 const [offsetX, offsetY] =
646 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
647 : [e.clientX, e.clientY];
648 let landing = document.elementFromPoint(offsetX, offsetY);
649 // Next condition: classList.contains(piece) fails because of marks
650 while (landing.tagName == "IMG") landing = landing.parentNode;
651 if (this.start.id == landing.id) {
652 if (this.click == landing.id) {
653 // Second click on same square: cancel current move
654 this.possibleMoves = [];
657 } else this.click = landing.id;
661 // OK: process move attempt, landing is a square node
662 let endSquare = getSquareFromId(landing.id);
663 let moves = this.findMatchingMoves(endSquare);
664 this.possibleMoves = [];
665 if (moves.length > 1) {
666 this.clickTime = Date.now();
667 this.choices = moves;
668 } else if (moves.length == 1) this.play(moves[0]);
669 // else: forbidden move attempt
671 processArrowAttempt: function(e) {
672 // Obtain the arrow from start and end squares
673 const [offsetX, offsetY] = [e.clientX, e.clientY];
674 let landing = document.elementFromPoint(offsetX, offsetY);
675 // Next condition: classList.contains(piece) fails because of marks
676 while (landing.tagName == "IMG") landing = landing.parentNode;
677 if (this.startArrow.id == landing.id)
678 // Draw (or erase) a circle
679 this.$set(this.circles, landing.id, !this.circles[landing.id]);
681 // OK: add arrow, landing is a new square
682 const rect = landing.getBoundingClientRect();
685 x: this.startArrow.x,
689 x: rect.x + rect.width / 2,
690 y: rect.y + rect.width / 2
694 this.startArrow = null;
696 findMatchingMoves: function(endSquare) {
697 // Run through moves list and return the matching set (if promotions...)
699 this.possibleMoves.filter(m => {
700 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
704 play: function(move) {
705 this.$emit("play-move", move);
711 <style lang="sass" scoped>
712 // NOTE: no variants with reserve of size != 8
736 background-color: rgba(0,0,0,0)
739 background-color: #e6ee9c
741 background-color: skyblue
764 marker-end: url(#arrow)
770 background-color: rgba(204, 51, 0, 0.7) !important
772 background-color: rgba(204, 51, 0, 0.9) !important
774 .light-square.lichess
775 background-color: #f0d9b5;
777 background-color: #b58863;
779 .light-square.chesscom
780 background-color: #e5e5ca;
781 .dark-square.chesscom
782 background-color: #6f8f57;
784 .light-square.chesstempo
785 background-color: #dfdfdf;
786 .dark-square.chesstempo
787 background-color: #7287b6;
789 // TODO: no predefined highlight colors, but layers. How?
791 .light-square.lichess.highlight-light
792 background-color: #cdd26a
793 .dark-square.lichess.highlight-dark
794 background-color: #aaa23a
796 .light-square.chesscom.highlight-light
797 background-color: #f7f783
798 .dark-square.chesscom.highlight-dark
799 background-color: #bacb44
801 .light-square.chesstempo.highlight-light
802 background-color: #9f9fff
803 .dark-square.chesstempo.highlight-dark
804 background-color: #557fff