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 to highlight squares
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)
29 settings: store.state.settings
34 // Return empty div of class 'game' to avoid error when setting size
41 const [sizeX, sizeY] = [V.size.x, V.size.y];
42 // Precompute hints squares to facilitate rendering
43 let hintSquares = ArrayFun.init(sizeX, sizeY, false);
44 this.possibleMoves.forEach(m => {
45 hintSquares[m.end.x][m.end.y] = true;
47 // Also precompute in-check squares
48 let incheckSq = ArrayFun.init(sizeX, sizeY, false);
49 this.incheck.forEach(sq => {
50 incheckSq[sq[0]][sq[1]] = true;
53 const lm = this.lastMove;
55 this.settings.highlight &&
56 ["all","highlight"].includes(V.ShowMoves)
58 const orientation = !V.CanFlip ? "w" : this.orientation;
59 // Ensure that squares colors do not change when board is flipped
60 const lightSquareMod = (sizeX + sizeY) % 2;
61 const showPiece = (x, y) => {
63 this.vr.board[x][y] != V.EMPTY &&
64 (!this.vr.enlightened || this.analyze || this.score != "*" ||
65 (!!this.userColor && this.vr.enlightened[this.userColor][x][y]))
68 const inHighlight = (x, y) => {
69 return showLight && !!lm && (
70 (lm.end.x == x && lm.end.y == y) ||
71 (lm.start.x == x && lm.start.y == y));
73 const inShadow = (x, y) => {
77 this.vr.enlightened &&
78 (!this.userColor || !this.vr.enlightened[this.userColor][x][y])
81 // Create board element (+ reserves if needed by variant)
82 let elementArray = [];
91 [...Array(sizeX).keys()].map(i => {
92 const ci = orientation == "w" ? i : sizeX - i - 1;
99 style: { opacity: this.choices.length > 0 ? "0.5" : "1" }
101 [...Array(sizeY).keys()].map(j => {
102 const cj = orientation == "w" ? j : sizeY - j - 1;
104 if (showPiece(ci, cj)) {
110 !!this.selectedPiece &&
111 this.selectedPiece.parentNode.id == "sq-" + ci + "-" + cj
117 this.vr.board[ci][cj],
118 // Extra args useful for some variants:
127 if (this.settings.hints && hintSquares[ci][cj]) {
134 src: "/images/mark.svg"
139 const lightSquare = (ci + cj) % 2 == lightSquareMod;
145 ["board" + sizeY]: true,
146 "light-square": lightSquare,
147 "dark-square": !lightSquare,
148 [this.settings.bcolor]: true,
149 "in-shadow": inShadow(ci, cj),
150 "highlight-light": inHighlight(ci, cj) && lightSquare,
151 "highlight-dark": inHighlight(ci, cj) && !lightSquare,
152 "incheck-light": showLight && lightSquare && incheckSq[ci][cj],
153 "incheck-dark": showLight && !lightSquare && incheckSq[ci][cj]
156 id: getSquareId({ x: ci, y: cj })
165 if (!!this.vr.reserve) {
166 const playingColor = this.userColor || "w"; //default for an observer
167 const shiftIdx = playingColor == "w" ? 0 : 1;
168 let myReservePiecesArray = [];
169 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
170 const qty = this.vr.reserve[playingColor][V.RESERVE_PIECES[i]];
171 myReservePiecesArray.push(
175 class: { board: true, ["board" + sizeY]: true },
176 attrs: { id: getSquareId({ x: sizeX + shiftIdx, y: i }) },
177 style: { opacity: qty > 0 ? 1 : 0.35 }
181 class: { piece: true, reserve: true },
185 this.vr.getReservePpath(i, playingColor) +
189 h("sup", { class: { "reserve-count": true } }, [ qty ])
194 let oppReservePiecesArray = [];
195 const oppCol = V.GetOppCol(playingColor);
196 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
197 const qty = this.vr.reserve[oppCol][V.RESERVE_PIECES[i]];
198 oppReservePiecesArray.push(
202 class: { board: true, ["board" + sizeY]: true },
203 attrs: { id: getSquareId({ x: sizeX + (1 - shiftIdx), y: i }) },
204 style: { opacity: qty > 0 ? 1 : 0.35 }
208 class: { piece: true, reserve: true },
212 this.vr.getReservePpath(i, oppCol) +
216 h("sup", { class: { "reserve-count": true } }, [ qty ])
221 const myReserveTop = (
222 (playingColor == 'w' && orientation == 'b') ||
223 (playingColor == 'b' && orientation == 'w')
225 // Center reserves, assuming same number of pieces for each side:
226 const nbReservePieces = myReservePiecesArray.length;
227 const marginLeft = ((100 - nbReservePieces * (100 / sizeY)) / 2) + "%";
237 "margin-left": marginLeft
249 myReserveTop ? myReservePiecesArray : oppReservePiecesArray
262 "margin-left": marginLeft
274 myReserveTop ? oppReservePiecesArray : myReservePiecesArray
278 elementArray.push(reserveTop);
280 elementArray.push(gameDiv);
281 if (!!this.vr.reserve) elementArray.push(reserveBottom);
282 const boardElt = document.querySelector(".game");
283 if (this.choices.length > 0 && !!boardElt) {
284 // No choices to show at first drawing
285 const squareWidth = boardElt.offsetWidth / sizeY;
286 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
287 const maxNbeltsPerRow = Math.min(this.choices.length, sizeY);
288 let topOffset = offset[0] + (sizeY / 2) * squareWidth - squareWidth / 2;
289 let choicesHeight = squareWidth;
290 if (this.choices.length >= sizeY) {
291 // A second row is required (Eightpieces variant)
292 topOffset -= squareWidth / 2;
298 attrs: { id: "choices" },
299 class: { row: true },
301 top: topOffset + "px",
304 (squareWidth * Math.max(sizeY - this.choices.length, 0)) / 2 +
306 width: (maxNbeltsPerRow * squareWidth) + "px",
307 height: choicesHeight + "px"
313 this.choices.map(m => {
314 // A "choice" is a move
315 const applyMove = (e) => {
317 // Force a delay between move is shown and clicked
318 // (otherwise a "double-click" bug might occur)
319 if (Date.now() - this.clickTime < 200) return;
325 ? { touchend: applyMove }
326 : { mouseup: applyMove };
332 ["board" + sizeY]: true
335 width: (100 / maxNbeltsPerRow) + "%",
336 "padding-bottom": (100 / maxNbeltsPerRow) + "%"
345 m.appear[0].c + m.appear[0].p,
346 // Extra arg useful for some variants:
350 class: { "choice-piece": true },
358 elementArray.unshift(choices);
361 // NOTE: click = mousedown + mouseup
362 if (this.mobileBrowser) {
365 touchstart: this.mousedown,
366 touchmove: this.mousemove,
367 touchend: this.mouseup
373 mousedown: this.mousedown,
374 mousemove: this.mousemove,
375 mouseup: this.mouseup
379 return h("div", onEvents, elementArray);
382 mousedown: function(e) {
385 // Start square must contain a piece.
386 // NOTE: classList[0] is enough: 'piece' is the first assigned class
387 if (e.target.classList[0] != "piece") return;
388 let parent = e.target.parentNode; //surrounding square
389 // Show possible moves if current player allowed to play
390 const startSquare = getSquareFromId(parent.id);
391 this.possibleMoves = [];
392 const color = this.analyze ? this.vr.turn : this.userColor;
393 if (this.vr.canIplay(color, startSquare))
394 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
395 // For potential drag'n drop, remember start coordinates
396 // (to center the piece on mouse cursor)
397 let rect = parent.getBoundingClientRect();
399 x: rect.x + rect.width / 2,
400 y: rect.y + rect.width / 2,
403 // Add the moving piece to the board, just after current image
404 this.selectedPiece = e.target.cloneNode();
406 this.selectedPiece.style,
408 position: "absolute",
410 display: "inline-block",
414 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
416 this.processMoveAttempt(e);
419 mousemove: function(e) {
420 if (!this.selectedPiece) return;
422 // There is an active element: move it around
423 const [offsetX, offsetY] =
425 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
426 : [e.clientX, e.clientY];
428 this.selectedPiece.style,
430 left: offsetX - this.start.x + "px",
431 top: offsetY - this.start.y + "px"
435 mouseup: function(e) {
436 if (!this.selectedPiece) return;
438 // Drag'n drop. Selected piece is no longer needed:
439 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
440 delete this.selectedPiece;
441 this.selectedPiece = null;
442 this.processMoveAttempt(e);
444 processMoveAttempt: function(e) {
445 // Obtain the move from start and end squares
446 const [offsetX, offsetY] =
448 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
449 : [e.clientX, e.clientY];
450 let landing = document.elementFromPoint(offsetX, offsetY);
451 // Next condition: classList.contains(piece) fails because of marks
452 while (landing.tagName == "IMG") landing = landing.parentNode;
453 if (this.start.id == landing.id) {
454 if (this.click == landing.id) {
455 // Second click on same square: cancel current move
456 this.possibleMoves = [];
459 } else this.click = landing.id;
463 // OK: process move attempt, landing is a square node
464 let endSquare = getSquareFromId(landing.id);
465 let moves = this.findMatchingMoves(endSquare);
466 this.possibleMoves = [];
467 if (moves.length > 1) {
468 this.clickTime = Date.now();
469 this.choices = moves;
470 } else if (moves.length == 1) this.play(moves[0]);
471 // else: forbidden move attempt
473 findMatchingMoves: function(endSquare) {
474 // Run through moves list and return the matching set (if promotions...)
476 this.possibleMoves.filter(m => {
477 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
481 play: function(move) {
482 this.$emit("play-move", move);
488 <style lang="sass" scoped>
498 // NOTE: no variants with reserve of size != 8
513 background-color: rgba(0,0,0,0)
516 background-color: #e6ee9c
518 background-color: skyblue
530 background-color: rgba(204, 51, 0, 0.7) !important
532 background-color: rgba(204, 51, 0, 0.9) !important
534 .light-square.lichess
535 background-color: #f0d9b5;
537 background-color: #b58863;
539 .light-square.chesscom
540 background-color: #e5e5ca;
541 .dark-square.chesscom
542 background-color: #6f8f57;
544 .light-square.chesstempo
545 background-color: #dfdfdf;
546 .dark-square.chesstempo
547 background-color: #7287b6;
549 // TODO: no predefined highlight colors, but layers. How?
551 .light-square.lichess.highlight-light
552 background-color: #cdd26a
553 .dark-square.lichess.highlight-dark
554 background-color: #aaa23a
556 .light-square.chesscom.highlight-light
557 background-color: #f7f783
558 .dark-square.chesscom.highlight-dark
559 background-color: #bacb44
561 .light-square.chesstempo.highlight-light
562 background-color: #9f9fff
563 .dark-square.chesstempo.highlight-dark
564 background-color: #557fff