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)
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,
156 "incheck-light": showCheck && lightSquare && incheckSq[ci][cj],
157 "incheck-dark": showCheck && !lightSquare && incheckSq[ci][cj]
160 id: getSquareId({ x: ci, y: cj })
169 if (!!this.vr.reserve) {
170 const playingColor = this.userColor || "w"; //default for an observer
171 const shiftIdx = playingColor == "w" ? 0 : 1;
172 let myReservePiecesArray = [];
173 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
174 const qty = this.vr.reserve[playingColor][V.RESERVE_PIECES[i]];
175 myReservePiecesArray.push(
179 "class": { board: true, ["board" + sizeY]: true },
180 attrs: { id: getSquareId({ x: sizeX + shiftIdx, y: i }) },
181 style: { opacity: qty > 0 ? 1 : 0.35 }
185 "class": { piece: true, reserve: true },
189 this.vr.getReservePpath(i, playingColor) +
193 h("sup", { "class": { "reserve-count": true } }, [ qty ])
198 let oppReservePiecesArray = [];
199 const oppCol = V.GetOppCol(playingColor);
200 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
201 const qty = this.vr.reserve[oppCol][V.RESERVE_PIECES[i]];
202 oppReservePiecesArray.push(
206 "class": { board: true, ["board" + sizeY]: true },
207 attrs: { id: getSquareId({ x: sizeX + (1 - shiftIdx), y: i }) },
208 style: { opacity: qty > 0 ? 1 : 0.35 }
212 "class": { piece: true, reserve: true },
216 this.vr.getReservePpath(i, oppCol) +
220 h("sup", { "class": { "reserve-count": true } }, [ qty ])
225 const myReserveTop = (
226 (playingColor == 'w' && orientation == 'b') ||
227 (playingColor == 'b' && orientation == 'w')
229 // Center reserves, assuming same number of pieces for each side:
230 const nbReservePieces = myReservePiecesArray.length;
231 const marginLeft = ((100 - nbReservePieces * (100 / sizeY)) / 2) + "%";
241 "margin-left": marginLeft
253 myReserveTop ? myReservePiecesArray : oppReservePiecesArray
266 "margin-left": marginLeft
278 myReserveTop ? oppReservePiecesArray : myReservePiecesArray
282 elementArray.push(reserveTop);
284 elementArray.push(gameDiv);
285 if (!!this.vr.reserve) elementArray.push(reserveBottom);
286 const boardElt = document.querySelector(".game");
287 if (this.choices.length > 0 && !!boardElt) {
288 // No choices to show at first drawing
289 const squareWidth = boardElt.offsetWidth / sizeY;
290 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
291 const maxNbeltsPerRow = Math.min(this.choices.length, sizeY);
292 let topOffset = offset[0] + (sizeY / 2) * squareWidth - squareWidth / 2;
293 let choicesHeight = squareWidth;
294 if (this.choices.length >= sizeY) {
295 // A second row is required (Eightpieces variant)
296 topOffset -= squareWidth / 2;
302 attrs: { id: "choices" },
303 "class": { row: true },
305 top: topOffset + "px",
308 (squareWidth * Math.max(sizeY - this.choices.length, 0)) / 2 +
310 width: (maxNbeltsPerRow * squareWidth) + "px",
311 height: choicesHeight + "px"
317 "class": { "full-width": true }
319 this.choices.map(m => {
320 // A "choice" is a move
321 const applyMove = (e) => {
323 // Force a delay between move is shown and clicked
324 // (otherwise a "double-click" bug might occur)
325 if (Date.now() - this.clickTime < 200) return;
331 ? { touchend: applyMove }
332 : { mouseup: applyMove };
338 ["board" + sizeY]: true
341 width: (100 / maxNbeltsPerRow) + "%",
342 "padding-bottom": (100 / maxNbeltsPerRow) + "%"
350 // orientation: extra arg useful for some variants:
351 this.vr.getPPpath(m, this.orientation) +
354 "class": { "choice-piece": true },
362 elementArray.unshift(choices);
365 // NOTE: click = mousedown + mouseup
366 if (this.mobileBrowser) {
369 touchstart: this.mousedown,
370 touchmove: this.mousemove,
371 touchend: this.mouseup
377 mousedown: this.mousedown,
378 mousemove: this.mousemove,
379 mouseup: this.mouseup
383 return h("div", onEvents, elementArray);
386 mousedown: function(e) {
389 // Start square must contain a piece.
390 // NOTE: classList[0] is enough: 'piece' is the first assigned class
391 if (e.target.classList[0] != "piece") return;
392 let parent = e.target.parentNode; //surrounding square
393 // Show possible moves if current player allowed to play
394 const startSquare = getSquareFromId(parent.id);
395 this.possibleMoves = [];
396 const color = this.analyze ? this.vr.turn : this.userColor;
397 if (this.vr.canIplay(color, startSquare))
398 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
399 // For potential drag'n drop, remember start coordinates
400 // (to center the piece on mouse cursor)
401 let rect = parent.getBoundingClientRect();
403 x: rect.x + rect.width / 2,
404 y: rect.y + rect.width / 2,
407 // Add the moving piece to the board, just after current image
408 this.selectedPiece = e.target.cloneNode();
410 this.selectedPiece.style,
412 position: "absolute",
414 display: "inline-block",
418 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
420 this.processMoveAttempt(e);
423 mousemove: function(e) {
424 if (!this.selectedPiece) return;
426 // There is an active element: move it around
427 const [offsetX, offsetY] =
429 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
430 : [e.clientX, e.clientY];
432 this.selectedPiece.style,
434 left: offsetX - this.start.x + "px",
435 top: offsetY - this.start.y + "px"
439 mouseup: function(e) {
440 if (!this.selectedPiece) return;
442 // Drag'n drop. Selected piece is no longer needed:
443 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
444 delete this.selectedPiece;
445 this.selectedPiece = null;
446 this.processMoveAttempt(e);
448 processMoveAttempt: function(e) {
449 // Obtain the move from start and end squares
450 const [offsetX, offsetY] =
452 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
453 : [e.clientX, e.clientY];
454 let landing = document.elementFromPoint(offsetX, offsetY);
455 // Next condition: classList.contains(piece) fails because of marks
456 while (landing.tagName == "IMG") landing = landing.parentNode;
457 if (this.start.id == landing.id) {
458 if (this.click == landing.id) {
459 // Second click on same square: cancel current move
460 this.possibleMoves = [];
463 } else this.click = landing.id;
467 // OK: process move attempt, landing is a square node
468 let endSquare = getSquareFromId(landing.id);
469 let moves = this.findMatchingMoves(endSquare);
470 this.possibleMoves = [];
471 if (moves.length > 1) {
472 this.clickTime = Date.now();
473 this.choices = moves;
474 } else if (moves.length == 1) this.play(moves[0]);
475 // else: forbidden move attempt
477 findMatchingMoves: function(endSquare) {
478 // Run through moves list and return the matching set (if promotions...)
480 this.possibleMoves.filter(m => {
481 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
485 play: function(move) {
486 this.$emit("play-move", move);
492 <style lang="sass" scoped>
493 // NOTE: no variants with reserve of size != 8
517 background-color: rgba(0,0,0,0)
520 background-color: #e6ee9c
522 background-color: skyblue
534 background-color: rgba(204, 51, 0, 0.7) !important
536 background-color: rgba(204, 51, 0, 0.9) !important
538 .light-square.lichess
539 background-color: #f0d9b5;
541 background-color: #b58863;
543 .light-square.chesscom
544 background-color: #e5e5ca;
545 .dark-square.chesscom
546 background-color: #6f8f57;
548 .light-square.chesstempo
549 background-color: #dfdfdf;
550 .dark-square.chesstempo
551 background-color: #7287b6;
553 // TODO: no predefined highlight colors, but layers. How?
555 .light-square.lichess.highlight-light
556 background-color: #cdd26a
557 .dark-square.lichess.highlight-dark
558 background-color: #aaa23a
560 .light-square.chesscom.highlight-light
561 background-color: #f7f783
562 .dark-square.chesscom.highlight-dark
563 background-color: #bacb44
565 .light-square.chesstempo.highlight-light
566 background-color: #9f9fff
567 .dark-square.chesstempo.highlight-dark
568 background-color: #557fff