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)
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)
59 this.settings.highlight &&
60 ["all","highlight","byrow"].includes(V.ShowMoves)
62 const orientation = !V.CanFlip ? "w" : this.orientation;
63 // Ensure that squares colors do not change when board is flipped
64 const lightSquareMod = (sizeX + sizeY) % 2;
65 const showPiece = (x, y) => {
67 this.vr.board[x][y] != V.EMPTY &&
68 (!this.vr.enlightened || this.analyze || this.score != "*" ||
69 (!!this.userColor && this.vr.enlightened[this.userColor][x][y]))
72 const inHighlight = (x, y) => {
73 return showLight && !!lm && (
74 (lm.end.x == x && lm.end.y == y) ||
75 (lm.start.x == x && lm.start.y == y));
77 const inShadow = (x, y) => {
81 this.vr.enlightened &&
82 (!this.userColor || !this.vr.enlightened[this.userColor][x][y])
85 // Create board element (+ reserves if needed by variant)
86 let elementArray = [];
95 [...Array(sizeX).keys()].map(i => {
96 const ci = orientation == "w" ? i : sizeX - i - 1;
103 style: { opacity: this.choices.length > 0 ? "0.5" : "1" }
105 [...Array(sizeY).keys()].map(j => {
106 const cj = orientation == "w" ? j : sizeY - j - 1;
108 if (showPiece(ci, cj)) {
114 !!this.selectedPiece &&
115 this.selectedPiece.parentNode.id == "sq-" + ci + "-" + cj
121 this.vr.board[ci][cj],
122 // Extra args useful for some variants:
131 if (this.settings.hints && hintSquares[ci][cj]) {
138 src: "/images/mark.svg"
143 const lightSquare = (ci + cj) % 2 == lightSquareMod;
149 ["board" + sizeY]: true,
150 "light-square": lightSquare,
151 "dark-square": !lightSquare,
152 [this.settings.bcolor]: true,
153 "in-shadow": inShadow(ci, cj),
154 "highlight-light": inHighlight(ci, cj) && lightSquare,
155 "highlight-dark": inHighlight(ci, cj) && !lightSquare,
157 showCheck && lightSquare && incheckSq[ci][cj],
159 showCheck && !lightSquare && incheckSq[ci][cj]
162 id: getSquareId({ x: ci, y: cj })
171 if (!!this.vr.reserve) {
172 const playingColor = this.userColor || "w"; //default for an observer
173 const shiftIdx = playingColor == "w" ? 0 : 1;
174 let myReservePiecesArray = [];
175 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
176 const qty = this.vr.reserve[playingColor][V.RESERVE_PIECES[i]];
177 myReservePiecesArray.push(
181 "class": { board: true, ["board" + sizeY]: true },
182 attrs: { id: getSquareId({ x: sizeX + shiftIdx, y: i }) },
183 style: { opacity: qty > 0 ? 1 : 0.35 }
187 "class": { piece: true, reserve: true },
191 this.vr.getReservePpath(i, playingColor) +
195 h("sup", { "class": { "reserve-count": true } }, [ qty ])
200 let oppReservePiecesArray = [];
201 const oppCol = V.GetOppCol(playingColor);
202 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
203 const qty = this.vr.reserve[oppCol][V.RESERVE_PIECES[i]];
204 oppReservePiecesArray.push(
208 "class": { board: true, ["board" + sizeY]: true },
209 attrs: { id: getSquareId({ x: sizeX + (1 - shiftIdx), y: i }) },
210 style: { opacity: qty > 0 ? 1 : 0.35 }
214 "class": { piece: true, reserve: true },
218 this.vr.getReservePpath(i, oppCol) +
222 h("sup", { "class": { "reserve-count": true } }, [ qty ])
227 const myReserveTop = (
228 (playingColor == 'w' && orientation == 'b') ||
229 (playingColor == 'b' && orientation == 'w')
231 // Center reserves, assuming same number of pieces for each side:
232 const nbReservePieces = myReservePiecesArray.length;
233 const marginLeft = ((100 - nbReservePieces * (100 / sizeY)) / 2) + "%";
243 "margin-left": marginLeft
255 myReserveTop ? myReservePiecesArray : oppReservePiecesArray
268 "margin-left": marginLeft
280 myReserveTop ? oppReservePiecesArray : myReservePiecesArray
284 elementArray.push(reserveTop);
286 elementArray.push(gameDiv);
287 if (!!this.vr.reserve) elementArray.push(reserveBottom);
288 const boardElt = document.querySelector(".game");
289 if (this.choices.length > 0 && !!boardElt) {
290 // No choices to show at first drawing
291 const squareWidth = boardElt.offsetWidth / sizeY;
292 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
293 const maxNbeltsPerRow = Math.min(this.choices.length, sizeY);
294 let topOffset = offset[0] + (sizeY / 2) * squareWidth - squareWidth / 2;
295 let choicesHeight = squareWidth;
296 if (this.choices.length >= sizeY) {
297 // A second row is required (Eightpieces variant)
298 topOffset -= squareWidth / 2;
304 attrs: { id: "choices" },
305 "class": { row: true },
307 top: topOffset + "px",
310 (squareWidth * Math.max(sizeY - this.choices.length, 0)) / 2 +
312 width: (maxNbeltsPerRow * squareWidth) + "px",
313 height: choicesHeight + "px"
319 "class": { "full-width": true }
321 this.choices.map(m => {
322 // A "choice" is a move
323 const applyMove = (e) => {
325 // Force a delay between move is shown and clicked
326 // (otherwise a "double-click" bug might occur)
327 if (Date.now() - this.clickTime < 200) return;
333 ? { touchend: applyMove }
334 : { mouseup: applyMove };
340 ["board" + sizeY]: true
343 width: (100 / maxNbeltsPerRow) + "%",
344 "padding-bottom": (100 / maxNbeltsPerRow) + "%"
352 // orientation: extra arg useful for some variants:
353 this.vr.getPPpath(m, this.orientation) +
356 "class": { "choice-piece": true },
364 elementArray.unshift(choices);
367 // NOTE: click = mousedown + mouseup
368 if (this.mobileBrowser) {
371 touchstart: this.mousedown,
372 touchmove: this.mousemove,
373 touchend: this.mouseup
379 mousedown: this.mousedown,
380 mousemove: this.mousemove,
381 mouseup: this.mouseup
385 return h("div", onEvents, elementArray);
388 mousedown: function(e) {
391 // NOTE: classList[0] is enough: 'piece' is the first assigned class
392 const withPiece = e.target.classList[0] == "piece";
393 // Emit the click event which could be used by some variants
396 getSquareFromId(withPiece ? e.target.parentNode.id : e.target.id)
398 // Start square must contain a piece.
399 if (!withPiece) return;
400 let parent = e.target.parentNode; //surrounding square
401 // Show possible moves if current player allowed to play
402 const startSquare = getSquareFromId(parent.id);
403 this.possibleMoves = [];
404 const color = this.analyze ? this.vr.turn : this.userColor;
405 if (this.vr.canIplay(color, startSquare))
406 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
407 // For potential drag'n drop, remember start coordinates
408 // (to center the piece on mouse cursor)
409 let rect = parent.getBoundingClientRect();
411 x: rect.x + rect.width / 2,
412 y: rect.y + rect.width / 2,
415 // Add the moving piece to the board, just after current image
416 this.selectedPiece = e.target.cloneNode();
418 this.selectedPiece.style,
420 position: "absolute",
422 display: "inline-block",
426 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
428 this.processMoveAttempt(e);
431 mousemove: function(e) {
432 if (!this.selectedPiece) return;
434 // There is an active element: move it around
435 const [offsetX, offsetY] =
437 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
438 : [e.clientX, e.clientY];
440 this.selectedPiece.style,
442 left: offsetX - this.start.x + "px",
443 top: offsetY - this.start.y + "px"
447 mouseup: function(e) {
448 if (!this.selectedPiece) return;
450 // Drag'n drop. Selected piece is no longer needed:
451 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
452 delete this.selectedPiece;
453 this.selectedPiece = null;
454 this.processMoveAttempt(e);
456 processMoveAttempt: function(e) {
457 // Obtain the move from start and end squares
458 const [offsetX, offsetY] =
460 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
461 : [e.clientX, e.clientY];
462 let landing = document.elementFromPoint(offsetX, offsetY);
463 // Next condition: classList.contains(piece) fails because of marks
464 while (landing.tagName == "IMG") landing = landing.parentNode;
465 if (this.start.id == landing.id) {
466 if (this.click == landing.id) {
467 // Second click on same square: cancel current move
468 this.possibleMoves = [];
471 } else this.click = landing.id;
475 // OK: process move attempt, landing is a square node
476 let endSquare = getSquareFromId(landing.id);
477 let moves = this.findMatchingMoves(endSquare);
478 this.possibleMoves = [];
479 if (moves.length > 1) {
480 this.clickTime = Date.now();
481 this.choices = moves;
482 } else if (moves.length == 1) this.play(moves[0]);
483 // else: forbidden move attempt
485 findMatchingMoves: function(endSquare) {
486 // Run through moves list and return the matching set (if promotions...)
488 this.possibleMoves.filter(m => {
489 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
493 play: function(move) {
494 this.$emit("play-move", move);
500 <style lang="sass" scoped>
501 // NOTE: no variants with reserve of size != 8
525 background-color: rgba(0,0,0,0)
528 background-color: #e6ee9c
530 background-color: skyblue
542 background-color: rgba(204, 51, 0, 0.7) !important
544 background-color: rgba(204, 51, 0, 0.9) !important
546 .light-square.lichess
547 background-color: #f0d9b5;
549 background-color: #b58863;
551 .light-square.chesscom
552 background-color: #e5e5ca;
553 .dark-square.chesscom
554 background-color: #6f8f57;
556 .light-square.chesstempo
557 background-color: #dfdfdf;
558 .dark-square.chesstempo
559 background-color: #7287b6;
561 // TODO: no predefined highlight colors, but layers. How?
563 .light-square.lichess.highlight-light
564 background-color: #cdd26a
565 .dark-square.lichess.highlight-dark
566 background-color: #aaa23a
568 .light-square.chesscom.highlight-light
569 background-color: #f7f783
570 .dark-square.chesscom.highlight-dark
571 background-color: #bacb44
573 .light-square.chesstempo.highlight-light
574 background-color: #9f9fff
575 .dark-square.chesstempo.highlight-dark
576 background-color: #557fff