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 if (V.OnBoard(m.start.x, m.start.y))
64 lmHighlights[m.start.x + sizeX * m.start.y] = true;
65 if (V.OnBoard(m.end.x, m.end.y))
66 lmHighlights[m.end.x + sizeX * m.end.y] = true;
70 this.settings.highlight &&
71 ["all","highlight"].includes(V.ShowMoves)
74 this.settings.highlight &&
75 ["all","highlight","byrow"].includes(V.ShowMoves)
77 const orientation = !V.CanFlip ? "w" : this.orientation;
78 // Ensure that squares colors do not change when board is flipped
79 const lightSquareMod = (sizeX + sizeY) % 2;
80 const showPiece = (x, y) => {
82 this.vr.board[x][y] != V.EMPTY &&
83 (!this.vr.enlightened || this.analyze || this.score != "*" ||
84 (!!this.userColor && this.vr.enlightened[this.userColor][x][y]))
87 const inHighlight = (x, y) => {
88 return showLight && !!lmHighlights[x + sizeX * y];
90 const inShadow = (x, y) => {
94 this.vr.enlightened &&
95 (!this.userColor || !this.vr.enlightened[this.userColor][x][y])
98 // Create board element (+ reserves if needed by variant)
99 let elementArray = [];
108 [...Array(sizeX).keys()].map(i => {
109 const ci = orientation == "w" ? i : sizeX - i - 1;
116 style: { opacity: this.choices.length > 0 ? "0.5" : "1" }
118 [...Array(sizeY).keys()].map(j => {
119 const cj = orientation == "w" ? j : sizeY - j - 1;
120 const squareId = "sq-" + ci + "-" + cj;
122 if (showPiece(ci, cj)) {
128 !!this.selectedPiece &&
129 this.selectedPiece.parentNode.id == squareId
135 this.vr.board[ci][cj],
136 // Extra args useful for some variants:
145 if (this.settings.hints && hintSquares[ci][cj]) {
152 src: "/images/mark.svg"
157 if (!!this.circles[squareId]) {
161 "circle-square": true
164 src: "/images/circle.svg"
169 const lightSquare = (ci + cj) % 2 == lightSquareMod;
175 ["board" + sizeY]: true,
176 "light-square": lightSquare,
177 "dark-square": !lightSquare,
178 [this.settings.bcolor]: true,
179 "in-shadow": inShadow(ci, cj),
180 "highlight-light": inHighlight(ci, cj) && lightSquare,
181 "highlight-dark": inHighlight(ci, cj) && !lightSquare,
183 showCheck && lightSquare && incheckSq[ci][cj],
185 showCheck && !lightSquare && incheckSq[ci][cj]
188 id: getSquareId({ x: ci, y: cj })
197 if (!!this.vr.reserve) {
198 const playingColor = this.userColor || "w"; //default for an observer
199 const shiftIdx = playingColor == "w" ? 0 : 1;
200 let myReservePiecesArray = [];
201 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
202 const qty = this.vr.reserve[playingColor][V.RESERVE_PIECES[i]];
203 myReservePiecesArray.push(
207 "class": { board: true, ["board" + sizeY]: true },
208 attrs: { id: getSquareId({ x: sizeX + shiftIdx, y: i }) },
209 style: { opacity: qty > 0 ? 1 : 0.35 }
213 "class": { piece: true, reserve: true },
217 this.vr.getReservePpath(i, playingColor) +
221 h("sup", { "class": { "reserve-count": true } }, [ qty ])
226 let oppReservePiecesArray = [];
227 const oppCol = V.GetOppCol(playingColor);
228 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
229 const qty = this.vr.reserve[oppCol][V.RESERVE_PIECES[i]];
230 oppReservePiecesArray.push(
234 "class": { board: true, ["board" + sizeY]: true },
235 attrs: { id: getSquareId({ x: sizeX + (1 - shiftIdx), y: i }) },
236 style: { opacity: qty > 0 ? 1 : 0.35 }
240 "class": { piece: true, reserve: true },
244 this.vr.getReservePpath(i, oppCol) +
248 h("sup", { "class": { "reserve-count": true } }, [ qty ])
253 const myReserveTop = (
254 (playingColor == 'w' && orientation == 'b') ||
255 (playingColor == 'b' && orientation == 'w')
257 // Center reserves, assuming same number of pieces for each side:
258 const nbReservePieces = myReservePiecesArray.length;
259 const marginLeft = ((100 - nbReservePieces * (100 / sizeY)) / 2) + "%";
269 "margin-left": marginLeft
281 myReserveTop ? myReservePiecesArray : oppReservePiecesArray
294 "margin-left": marginLeft
306 myReserveTop ? oppReservePiecesArray : myReservePiecesArray
310 elementArray.push(reserveTop);
312 elementArray.push(gameDiv);
313 if (!!this.vr.reserve) elementArray.push(reserveBottom);
314 const boardElt = document.querySelector(".game");
315 // boardElt might be undefine (at first drawing),
316 // but it won't be used in this case.
317 const squareWidth = (!!boardElt ? boardElt.offsetWidth / sizeY : 42);
318 if (this.choices.length > 0 && !!boardElt) {
319 // No choices to show at first drawing
320 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
321 const maxNbeltsPerRow = Math.min(this.choices.length, sizeY);
322 let topOffset = offset[0] + (sizeY / 2) * squareWidth - squareWidth / 2;
323 let choicesHeight = squareWidth;
324 if (this.choices.length >= sizeY) {
325 // A second row is required (Eightpieces variant)
326 topOffset -= squareWidth / 2;
332 attrs: { id: "choices" },
333 "class": { row: true },
335 top: topOffset + "px",
338 (squareWidth * Math.max(sizeY - this.choices.length, 0)) / 2 +
340 width: (maxNbeltsPerRow * squareWidth) + "px",
341 height: choicesHeight + "px"
347 "class": { "full-width": true }
349 this.choices.map(m => {
350 // A "choice" is a move
351 const applyMove = (e) => {
353 // Force a delay between move is shown and clicked
354 // (otherwise a "double-click" bug might occur)
355 if (Date.now() - this.clickTime < 200) return;
361 ? { touchend: applyMove }
362 : { mouseup: applyMove };
368 ["board" + sizeY]: true
371 width: (100 / maxNbeltsPerRow) + "%",
372 "padding-bottom": (100 / maxNbeltsPerRow) + "%"
380 // orientation: extra arg useful for some variants:
381 this.vr.getPPpath(m, this.orientation) +
384 "class": { "choice-piece": true },
392 elementArray.unshift(choices);
395 !this.mobileBrowser &&
396 (this.arrows.length > 0 || this.movingArrow.x >= 0)
399 const arrowWidth = squareWidth / 4;
400 this.arrows.forEach(a => {
401 const endPoint = this.adjustEndArrow(a.start, a.end, squareWidth);
406 "class": { "svg-arrow": true },
409 "M" + a.start.x + "," + a.start.y + " " +
410 "L" + endPoint.x + "," + endPoint.y
412 style: "stroke-width:" + arrowWidth + "px"
418 if (this.movingArrow.x >= 0) {
420 this.adjustEndArrow(this.startArrow, this.movingArrow, squareWidth);
425 "class": { "svg-arrow": true },
428 "M" + this.startArrow.x + "," + this.startArrow.y + " " +
429 "L" + endPoint.x + "," + endPoint.y
431 style: "stroke-width:" + arrowWidth + "px"
437 // Add SVG element for drawing arrows
457 markerWidth: (2 * arrowWidth) + "px",
458 markerHeight: (3 * arrowWidth) + "px",
459 markerUnits: "userSpaceOnUse",
461 refY: (1.5 * arrowWidth) + "px",
469 "class": { "arrow-head": true },
472 "M0,0 L0," + (3 * arrowWidth) + " L" +
473 (2 * arrowWidth) + "," + (1.5 * arrowWidth) + " z"
487 // NOTE: click = mousedown + mouseup
488 if (this.mobileBrowser) {
491 touchstart: this.mousedown,
492 touchmove: this.mousemove,
493 touchend: this.mouseup
499 mousedown: this.mousedown,
500 mousemove: this.mousemove,
501 mouseup: this.mouseup,
502 contextmenu: this.blockContextMenu
506 return h("div", onEvents, elementArray);
509 blockContextMenu: function(e) {
514 cancelResetArrows: function() {
515 this.startArrow = null;
519 adjustEndArrow: function(start, end, squareWidth) {
520 // Simple heuristic for now, just remove 1/3 square.
521 // TODO: should depend on the orientation.
522 const delta = [end.x - start.x, end.y - start.y];
523 const dist = Math.sqrt(delta[0] * delta[0] + delta[1] * delta[1]);
524 const fracSqWidth = squareWidth / 3;
526 x: end.x - delta[0] * fracSqWidth / dist,
527 y: end.y - delta[1] * fracSqWidth / dist
530 mousedown: function(e) {
532 if (!this.mobileBrowser && e.which != 3)
533 // Cancel current drawing and circles, if any
534 this.cancelResetArrows();
535 if (this.mobileBrowser || e.which == 1) {
538 // NOTE: classList[0] is enough: 'piece' is the first assigned class
539 const withPiece = (e.target.classList[0] == "piece");
540 // Emit the click event which could be used by some variants
543 getSquareFromId(withPiece ? e.target.parentNode.id : e.target.id)
545 // Start square must contain a piece.
546 if (!withPiece) return;
547 let parent = e.target.parentNode; //surrounding square
548 // Show possible moves if current player allowed to play
549 const startSquare = getSquareFromId(parent.id);
550 this.possibleMoves = [];
551 const color = this.analyze ? this.vr.turn : this.userColor;
552 if (this.vr.canIplay(color, startSquare))
553 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
554 // For potential drag'n drop, remember start coordinates
555 // (to center the piece on mouse cursor)
556 const rect = parent.getBoundingClientRect();
558 x: rect.x + rect.width / 2,
559 y: rect.y + rect.width / 2,
562 // Add the moving piece to the board, just after current image
563 this.selectedPiece = e.target.cloneNode();
565 this.selectedPiece.style,
567 position: "absolute",
569 display: "inline-block",
573 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
575 this.processMoveAttempt(e);
577 } else if (e.which == 3) {
578 // Mouse right button
580 // Next loop because of potential marks
581 while (elem.tagName == "IMG") elem = elem.parentNode;
582 // To center the arrow in square:
583 const rect = elem.getBoundingClientRect();
585 x: rect.x + rect.width / 2,
586 y: rect.y + rect.width / 2,
591 mousemove: function(e) {
592 if (!this.selectedPiece && !this.startArrow) return;
594 if (!!this.selectedPiece) {
595 // There is an active element: move it around
596 const [offsetX, offsetY] =
598 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
599 : [e.clientX, e.clientY];
601 this.selectedPiece.style,
603 left: offsetX - this.start.x + "px",
604 top: offsetY - this.start.y + "px"
610 // Next loop because of potential marks
611 while (elem.tagName == "IMG") elem = elem.parentNode;
612 // To center the arrow in square:
613 if (elem.id != this.startArrow.id) {
614 const rect = elem.getBoundingClientRect();
616 x: rect.x + rect.width / 2,
617 y: rect.y + rect.width / 2
622 mouseup: function(e) {
624 if (this.mobileBrowser || e.which == 1) {
625 if (!this.selectedPiece) return;
626 // Drag'n drop. Selected piece is no longer needed:
627 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
628 delete this.selectedPiece;
629 this.selectedPiece = null;
630 this.processMoveAttempt(e);
631 } else if (e.which == 3) {
632 // Mouse right button
633 this.movingArrow = { x: -1, y: -1 };
634 this.processArrowAttempt(e);
637 // Called by BaseGame after partially undoing multi-moves:
638 resetCurrentAttempt: function() {
639 this.possibleMoves = [];
642 this.selectedPiece = null;
644 processMoveAttempt: function(e) {
645 // Obtain the move from start and end squares
646 const [offsetX, offsetY] =
648 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
649 : [e.clientX, e.clientY];
650 let landing = document.elementFromPoint(offsetX, offsetY);
651 // Next condition: classList.contains(piece) fails because of marks
652 while (landing.tagName == "IMG") landing = landing.parentNode;
653 if (this.start.id == landing.id) {
654 if (this.click == landing.id) {
655 // Second click on same square: cancel current move
656 this.possibleMoves = [];
659 } else this.click = landing.id;
663 // OK: process move attempt, landing is a square node
664 let endSquare = getSquareFromId(landing.id);
665 let moves = this.findMatchingMoves(endSquare);
666 this.possibleMoves = [];
667 if (moves.length > 1) {
668 this.clickTime = Date.now();
669 this.choices = moves;
670 } else if (moves.length == 1) this.play(moves[0]);
671 // else: forbidden move attempt
673 processArrowAttempt: function(e) {
674 // Obtain the arrow from start and end squares
675 const [offsetX, offsetY] = [e.clientX, e.clientY];
676 let landing = document.elementFromPoint(offsetX, offsetY);
677 // Next condition: classList.contains(piece) fails because of marks
678 while (landing.tagName == "IMG") landing = landing.parentNode;
679 if (this.startArrow.id == landing.id)
680 // Draw (or erase) a circle
681 this.$set(this.circles, landing.id, !this.circles[landing.id]);
683 // OK: add arrow, landing is a new square
684 const rect = landing.getBoundingClientRect();
687 x: this.startArrow.x,
691 x: rect.x + rect.width / 2,
692 y: rect.y + rect.width / 2
696 this.startArrow = null;
698 findMatchingMoves: function(endSquare) {
699 // Run through moves list and return the matching set (if promotions...)
701 this.possibleMoves.filter(m => {
702 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
706 play: function(move) {
707 this.$emit("play-move", move);
713 <style lang="sass" scoped>
714 @import "@/styles/_board_squares_img.sass";
716 // NOTE: no variants with reserve of size != 8
740 background-color: rgba(0,0,0,0)
743 background-color: #e6ee9c
745 background-color: skyblue
768 marker-end: url(#arrow)
774 background-color: rgba(204, 51, 0, 0.7) !important
776 background-color: rgba(204, 51, 0, 0.9) !important
778 .light-square.lichess
779 background-color: #f0d9b5;
781 background-color: #b58863;
783 .light-square.chesscom
784 background-color: #e5e5ca;
785 .dark-square.chesscom
786 background-color: #6f8f57;
788 .light-square.chesstempo
789 background-color: #dfdfdf;
790 .dark-square.chesstempo
791 background-color: #7287b6;
793 // TODO: no predefined highlight colors, but layers. How?
795 .light-square.lichess.highlight-light
796 background-color: #cdd26a
797 .dark-square.lichess.highlight-dark
798 background-color: #aaa23a
800 .light-square.chesscom.highlight-light
801 background-color: #f7f783
802 .dark-square.chesscom.highlight-dark
803 background-color: #bacb44
805 .light-square.chesstempo.highlight-light
806 background-color: #9f9fff
807 .dark-square.chesstempo.highlight-dark
808 background-color: #557fff