3 input#modalEog.modal(type="checkbox")
6 data-checkbox="modalEog"
9 label.modal-close(for="modalEog")
10 h3.section {{ endgameMessage }}
17 :analyze="mode=='analyze'"
19 :user-color="game.mycolor"
20 :orientation="orientation"
24 @click-square="clickSquare"
25 @rendered="adjustSize"
27 #turnIndicator(v-if="showTurn") {{ turn }}
28 #controls.button-group
29 button(@click="gotoBegin()")
30 img.inline(src="/images/icons/fast-forward_rev.svg")
31 button(@click="undo()")
32 img.inline(src="/images/icons/play_rev.svg")
33 button(v-if="canFlip" @click="flip()")
34 img.inline(src="/images/icons/flip.svg")
36 @click="runAutoplay()"
37 :class="{'in-autoplay': autoplay}"
39 img.inline(src="/images/icons/autoplay.svg")
40 button(@click="play()")
41 img.inline(src="/images/icons/play.svg")
42 button(@click="gotoEnd()")
43 img.inline(src="/images/icons/fast-forward.svg")
44 p#fenAnalyze(v-show="showFen") {{ (!!vr ? vr.getFen() : "") }}
49 :canAnalyze="canAnalyze"
50 :canDownload="allowDownloadPGN"
52 :message="game.scoreMsg"
53 :firstNum="firstMoveNumber"
58 @showrules="showRules"
59 @analyze="toggleAnalyze"
61 @redraw-board="redrawBoard"
67 import Board from "@/components/Board.vue";
68 import MoveList from "@/components/MoveList.vue";
69 import params from "@/parameters";
70 import { store } from "@/store";
71 import { getSquareId } from "@/utils/squareId";
72 import { getDate } from "@/utils/datetime";
73 import { processModalClick } from "@/utils/modalClick";
74 import { getScoreMessage } from "@/utils/scoring";
75 import { getFullNotation } from "@/utils/notation";
76 import { undoMove } from "@/utils/playUndo";
87 // NOTE: all following variables must be reset at the beginning of a game
88 vr: null, //VariantRules object, game state
93 score: "*", //'*' means 'unfinished'
95 cursor: -1, //index of the move just played
98 firstMoveNumber: 0, //for printing
99 incheck: [], //for Board
108 if (!this.vr) return "";
109 if (this.vr.showMoves != "all") {
111 (this.vr.turn == 'w' ? "White" : "Black") + " to move"];
113 // Cannot flip (racing king or circular chess), or Monochrome
115 this.vr.movesCount == 0 && this.game.mycolor == "w"
116 ? this.st.tr["It's your turn!"]
120 showFen: function() {
122 this.mode == "analyze" &&
123 this.$router.currentRoute.path.indexOf("/analyse") === -1
126 // TODO: is it OK to pass "computed" as properties?
127 // Also, some are seemingly not recomputed when vr is initialized.
128 showMoves: function() {
130 !!this.game.score && this.game.score != "*"
132 : (!!this.vr ? this.vr.showMoves : "none")
135 showTurn: function() {
137 !!this.game.score && this.game.score == '*' &&
140 this.vr.showMoves != "all" ||
142 this.vr.showFirstTurn
146 canAnalyze: function() {
148 (!this.game.mode || this.game.mode != "analyze") &&
149 !!this.vr && this.vr.canAnalyze
152 canFlip: function() {
153 return !!this.vr && this.vr.canFlip;
155 allowDownloadPGN: function() {
157 (!!this.game.score && this.game.score != "*") ||
158 (!!this.vr && !this.vr.someHiddenMoves)
162 created: function() {
163 if (!!this.game.fenStart) this.re_setVariables();
165 mounted: function() {
166 if (!("ontouchstart" in window)) {
168 const baseGameDiv = document.getElementById("baseGame");
169 baseGameDiv.tabIndex = 0;
170 baseGameDiv.addEventListener("click", this.focusBg);
171 baseGameDiv.addEventListener("keydown", this.handleKeys);
172 if (this.st.settings.scrollmove)
173 baseGameDiv.addEventListener("wheel", this.handleScroll);
175 document.getElementById("eogDiv")
176 .addEventListener("click", processModalClick);
178 beforeDestroy: function() {
179 // TODO: probably not required
180 this.autoplay = false;
183 focusBg: function() {
184 document.getElementById("baseGame").focus();
186 handleKeys: function(e) {
187 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
206 handleScroll: function(e) {
208 if (e.deltaY < 0) this.undo();
209 else if (e.deltaY > 0) this.play();
211 adjustSize: function() {
212 this.$refs["moveslist"].adjustBoard("vertical");
214 redrawBoard: function() {
215 this.$refs["board"].re_setDrawings();
217 showRules: function() {
218 // The button is here only on Game page:
219 document.getElementById("modalRules").checked = true;
221 re_setVariables: function(game) {
222 if (!game) game = this.game; //in case of...
223 this.endgameMessage = "";
224 // "w": default orientation for observed games
225 this.orientation = game.mycolor || "w";
226 this.mode = game.mode || game.type; //TODO: merge...
227 this.moves = JSON.parse(JSON.stringify(game.moves || []));
228 // Post-processing: decorate each move with notation and FEN
229 this.vr = new V(game.fenStart);
230 this.inMultimove = false; //in case of
231 if (!!this.$refs["board"])
233 this.$refs["board"].resetCurrentAttempt();
234 let analyseBtn = document.getElementById("analyzeBtn");
235 if (!!analyseBtn) analyseBtn.classList.remove("active");
236 const parsedFen = V.ParseFen(game.fenStart);
237 const firstMoveColor = parsedFen.turn;
238 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2) + 1;
239 let L = this.moves.length;
240 this.moves.forEach((move,idx) => {
241 // Strategy working also for multi-moves:
242 if (!Array.isArray(move)) move = [move];
244 m.notation = this.vr.getNotation(m);
245 m.unambiguous = V.GetUnambiguousNotation(m);
248 const Lm = move.length;
249 move[Lm - 1].fen = this.vr.getFen();
250 if (idx < L - 1 && this.vr.getCheckSquares().length > 0)
251 move[Lm - 1].notation += "+";
253 this.incheck = this.vr.getCheckSquares();
254 this.score = this.vr.getCurrentScore();
257 !Array.isArray(this.moves[L - 1])
258 ? [this.moves[L - 1]]
260 const Lm = move.length;
261 if (["1-0", "0-1"].includes(this.score)) move[Lm - 1].notation += "#";
262 else if (this.incheck.length > 0) move[Lm - 1].notation += "+";
264 if (this.score != '*') {
265 // Show score on screen
266 const message = getScoreMessage(this.score);
267 this.showEndgameMsg(this.score + " . " + this.st.tr[message]);
269 if (firstMoveColor == "b") {
270 // 'start' & 'end' is required for Board component
274 start: { x: -1, y: -1 },
275 end: { x: -1, y: -1 },
280 this.positionCursorTo(L - 1);
282 positionCursorTo: function(index) {
284 // Note: last move in moves array might be a multi-move
285 if (index >= 0) this.lastMove = this.moves[index];
286 else this.lastMove = null;
288 toggleAnalyze: function() {
289 // Freeze while choices are shown (and autoplay has priority)
292 this.$refs["board"].choices.length > 0 ||
297 if (this.mode != "analyze") {
298 // Enter analyze mode:
299 this.gameMode = this.mode; //was not 'analyze'
300 this.mode = "analyze";
301 if (this.inMultimove) this.cancelCurrentMultimove();
302 this.gameCursor = this.cursor;
303 this.gameMoves = JSON.parse(JSON.stringify(this.moves));
304 document.getElementById("analyzeBtn").classList.add("active");
307 // Exit analyze mode:
308 this.mode = this.gameMode;
309 this.cursor = this.gameCursor;
310 this.moves = this.gameMoves;
311 let fen = this.game.fenStart;
312 if (this.cursor >= 0) {
313 let mv = this.moves[this.cursor];
314 if (!Array.isArray(mv)) mv = [mv];
315 fen = mv[mv.length-1].fen;
317 this.vr = new V(fen);
318 this.inMultimove = false; //in case of
319 this.$refs["board"].resetCurrentAttempt(); //also in case of
320 this.incheck = this.vr.getCheckSquares();
321 if (this.cursor >= 0) this.lastMove = this.moves[this.cursor];
322 else this.lastMove = null;
323 document.getElementById("analyzeBtn").classList.remove("active");
326 download: function() {
327 const content = this.getPgn();
328 // Prepare and trigger download link
329 let downloadAnchor = document.getElementById("download");
330 downloadAnchor.setAttribute("download", "game.pgn");
331 downloadAnchor.href =
332 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
333 downloadAnchor.click();
337 pgn += '[Site "vchess.club"]\n';
338 pgn += '[Variant "' + this.game.vname + '"]\n';
339 const gdt = getDate(new Date(this.game.created || Date.now()));
340 pgn += '[Date "' + gdt + '"]\n';
341 pgn += '[White "' + this.game.players[0].name + '"]\n';
342 pgn += '[Black "' + this.game.players[1].name + '"]\n';
343 pgn += '[Fen "' + this.game.fenStart + '"]\n';
344 pgn += '[Result "' + this.game.score + '"]\n';
346 pgn += '[Url "' + params.serverUrl + '/game/' + this.game.id + '"]\n';
347 if (!!this.game.cadence)
348 pgn += '[Cadence "' + this.game.cadence + '"]\n';
349 pgn += '[Options "' + JSON.stringify(this.game.options) + '"]\n';
351 for (let i = 0; i < this.moves.length; i += 2) {
352 if (i > 0) pgn += " ";
353 // Adjust dots notation for a better display:
354 let fullNotation = getFullNotation(this.moves[i]);
355 if (fullNotation == "...") fullNotation = "..";
356 pgn += (i / 2 + this.firstMoveNumber) + "." + fullNotation;
357 if (i+1 < this.moves.length)
358 pgn += " " + getFullNotation(this.moves[i+1]);
361 for (let i = 0; i < this.moves.length; i += 2) {
362 const moveNumber = i / 2 + this.firstMoveNumber;
363 // Skip "dots move", useless for machine reading:
364 if (this.moves[i].notation != "...") {
365 pgn += moveNumber + ".w " +
366 getFullNotation(this.moves[i], "unambiguous") + "\n";
368 if (i+1 < this.moves.length) {
369 pgn += moveNumber + ".b " +
370 getFullNotation(this.moves[i+1], "unambiguous") + "\n";
375 showEndgameMsg: function(message) {
376 this.endgameMessage = message;
377 document.getElementById("modalEog").checked = true;
379 runAutoplay: function() {
381 this.autoplay = false;
382 if (this.stackToPlay.length > 0)
383 // Move(s) arrived in-between
384 this.play(this.stackToPlay.pop(), "received");
386 else if (this.cursor < this.moves.length - 1) {
387 this.autoplay = true;
388 this.play(null, null, null, "autoplay");
391 // Animate an elementary move
392 animateMove: function(move, callback) {
393 let startSquare = document.getElementById(getSquareId(move.start));
394 if (!startSquare) return; //shouldn't happen but...
395 let endSquare = document.getElementById(getSquareId(move.end));
396 let rectStart = startSquare.getBoundingClientRect();
397 let rectEnd = endSquare.getBoundingClientRect();
399 x: rectEnd.x - rectStart.x,
400 y: rectEnd.y - rectStart.y
402 let movingPiece = document.querySelector(
403 "#" + getSquareId(move.start) + " > img.piece"
405 // For some unknown reasons Opera get "movingPiece == null" error
406 // TODO: is it calling 'animate()' twice ? One extra time ?
407 if (!movingPiece) return;
408 const squares = document.getElementsByClassName("board");
409 for (let i = 0; i < squares.length; i++) {
410 let square = squares.item(i);
411 if (square.id != getSquareId(move.start))
412 // HACK for animation:
413 // (with positive translate, image slides "under background")
414 square.style.zIndex = "-1";
416 movingPiece.style.transform =
417 "translate(" + translation.x + "px," + translation.y + "px)";
418 movingPiece.style.transitionDuration = "0.25s";
419 movingPiece.style.zIndex = "3000";
421 for (let i = 0; i < squares.length; i++)
422 squares.item(i).style.zIndex = "auto";
423 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
428 emitFenIfAnalyze: function() {
429 if (this.game.mode == "analyze") {
430 let fen = this.game.fenStart;
431 if (!!this.lastMove) {
432 if (Array.isArray(this.lastMove)) {
433 const L = this.lastMove.length;
434 fen = this.lastMove[L-1].fen;
436 else fen = this.lastMove.fen;
438 this.$emit("fenchange", fen);
441 clickSquare: function(square) {
442 // Some variants make use of a single click at specific times:
443 const move_s = this.vr.doClick(square);
445 const playMove = () => {
446 if (!Array.isArray(move_s)) this.play(move_s);
447 else this.$refs["board"].choices = move_s;
449 if ("ontouchstart" in window) {
450 const squareId = "sq-" + square[0] + "-" + square[1];
451 const highlight = function(on, sq) {
452 let elt = document.getElementById(sq);
454 if (on) elt.classList.add("touch-hover");
455 else elt.classList.remove("touch-hover");
458 // Touch screen (smartphone): require confirmation
459 const squareStr = square[0] + "_" + square[1]
460 if (this.touchLastClick == squareId) {
461 highlight(false, squareId);
465 highlight(true, squareId);
466 highlight(false, this.touchLastClick);
468 this.touchLastClick = squareId;
473 // "light": if gotoMove() or gotoEnd()
474 play: function(move, received, light, autoplay) {
475 // Freeze while choices are shown:
477 !!this.$refs["board"].selectedPiece ||
478 this.$refs["board"].choices.length > 0
482 const navigate = !move;
483 // Forbid navigation during autoplay:
484 if (navigate && this.autoplay && !autoplay) return;
485 // Forbid playing outside analyze mode, except if move is received.
486 // Sufficient condition because Board already knows which turn it is.
488 this.mode != "analyze" &&
491 (this.game.score != "*" || this.cursor < this.moves.length - 1)
496 if (this.autoplay || this.inPlay) {
497 // Received moves while autoplaying are stacked,
498 // and in observed games they could arrive too fast:
499 this.stackToPlay.unshift(move);
502 if (this.mode == "analyze") this.toggleAnalyze();
503 if (this.cursor < this.moves.length - 1)
504 // To play a received move, cursor must be at the end of the game:
508 // The board may show some possible moves: (TODO: bad solution)
509 this.$refs["board"].resetCurrentAttempt();
510 const playSubmove = (smove) => {
511 smove.notation = this.vr.getNotation(smove);
512 smove.unambiguous = V.GetUnambiguousNotation(smove);
514 if (this.inMultimove && !!this.lastMove) {
515 if (!Array.isArray(this.lastMove))
516 this.lastMove = [this.lastMove, smove];
517 else this.lastMove.push(smove);
519 if (!this.inMultimove) {
521 this.lastMove = smove;
522 // Condition is "!navigate" but we mean "!this.autoplay"
524 if (this.cursor < this.moves.length - 1)
525 this.moves = this.moves.slice(0, this.cursor + 1);
526 this.moves.push(smove);
528 this.inMultimove = true; //potentially
531 else if (!navigate) {
532 // Already in the middle of a multi-move
533 const L = this.moves.length;
534 if (!Array.isArray(this.moves[L-1]))
535 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
536 else this.moves[L-1].push(smove);
539 const playMove = () => {
541 ["all", "highlight"].includes(V.ShowMoves) &&
542 (this.autoplay || !!received)
544 if (!Array.isArray(move)) move = [move];
547 const initurn = this.vr.turn;
548 (function executeMove() {
549 const smove = move[moveIdx++];
550 // NOTE: condition "smove.start.x >= 0" required for Dynamo,
551 // because second move may be empty. noHighlight condition
552 // is used at least for Chakart.
553 if (animate && smove.start.x >= 0 && !smove.end.noHighlight) {
554 self.animateMove(smove, () => {
556 if (moveIdx < move.length) setTimeout(executeMove, 500);
557 else afterMove(smove, initurn);
562 if (moveIdx < move.length) executeMove();
563 else afterMove(smove, initurn);
567 const computeScore = () => {
568 const score = this.vr.getCurrentScore();
570 if (["1-0", "0-1"].includes(score)) {
571 if (Array.isArray(this.lastMove)) {
572 const L = this.lastMove.length;
573 this.lastMove[L - 1].notation += "#";
575 else this.lastMove.notation += "#";
578 if (score != "*" && ["analyze", "versus"].includes(this.mode)) {
579 const message = getScoreMessage(score, V.ReverseColors);
580 // Show score on screen
581 this.showEndgameMsg(score + " . " + this.st.tr[message]);
585 const afterMove = (smove, initurn) => {
586 if (this.vr.turn != initurn) {
587 // Turn has changed: move is complete
589 // NOTE: only FEN of last sub-move is required (=> setting it here)
590 smove.fen = this.vr.getFen();
591 this.emitFenIfAnalyze();
592 this.inMultimove = false;
593 this.incheck = this.vr.getCheckSquares();
594 if (this.incheck.length > 0) smove.notation += "+";
595 this.score = computeScore();
597 if (this.cursor < this.moves.length - 1)
598 setTimeout(() => this.play(null, null, null, "autoplay"), 1000);
600 this.autoplay = false;
601 if (this.stackToPlay.length > 0)
602 // Move(s) arrived in-between
603 this.play(this.stackToPlay.pop(), "received");
606 if (this.mode != "analyze" && !navigate) {
608 // Post-processing (e.g. computer play).
609 const L = this.moves.length;
610 // NOTE: always emit the score, even in unfinished
611 this.$emit("newmove", this.moves[L-1], { score: this.score });
615 if (this.stackToPlay.length > 0)
616 // Move(s) arrived in-between
617 this.play(this.stackToPlay.pop(), "received");
622 // NOTE: navigate and received are mutually exclusive
624 // The move to navigate to is necessarily full:
625 if (this.cursor == this.moves.length - 1) return; //no more moves
626 move = this.moves[this.cursor + 1];
627 if (!this.autoplay) {
628 // Just play the move:
629 if (!Array.isArray(move)) move = [move];
630 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
632 this.lastMove = move;
633 this.incheck = this.vr.getCheckSquares();
634 this.score = computeScore();
635 this.emitFenIfAnalyze();
643 cancelCurrentMultimove: function() {
644 const L = this.moves.length;
645 let move = this.moves[L-1];
646 if (!Array.isArray(move)) move = [move];
647 for (let i = move.length - 1; i >= 0; i--) this.vr.undo(move[i]);
650 this.inMultimove = false;
652 cancelLastMove: function() {
653 // The last played move was canceled (corr game)
657 // "light": if gotoMove() or gotoBegin()
658 undo: function(move, light) {
661 !!this.$refs["board"].selectedPiece ||
662 this.$refs["board"].choices.length > 0
666 this.$refs["board"].resetCurrentAttempt();
667 if (this.inMultimove) {
668 this.cancelCurrentMultimove();
669 this.incheck = this.vr.getCheckSquares();
670 if (this.cursor >= 0) this.lastMove = this.moves[this.cursor];
671 else this.lastMove = null;
676 this.moves.length > 0 && this.moves[0].notation == "..."
679 if (this.cursor < minCursor) return; //no more moves
680 move = this.moves[this.cursor];
682 this.$refs["board"].resetCurrentAttempt();
683 undoMove(move, this.vr);
684 if (light) this.cursor--;
686 this.positionCursorTo(this.cursor - 1);
687 this.incheck = this.vr.getCheckSquares();
688 this.emitFenIfAnalyze();
692 gotoMove: function(index) {
695 !!this.$refs["board"].selectedPiece ||
696 this.$refs["board"].choices.length > 0
700 this.$refs["board"].resetCurrentAttempt();
701 if (this.inMultimove) this.cancelCurrentMultimove();
702 if (index == this.cursor) return;
703 if (index < this.cursor) {
704 while (this.cursor > index)
705 this.undo(null, null, "light");
708 // index > this.cursor)
709 while (this.cursor < index)
710 this.play(null, null, "light");
712 // NOTE: next line also re-assign cursor, but it's very light
713 this.positionCursorTo(index);
714 this.incheck = this.vr.getCheckSquares();
715 this.emitFenIfAnalyze();
717 gotoBegin: function() {
720 !!this.$refs["board"].selectedPiece ||
721 this.$refs["board"].choices.length > 0
725 this.$refs["board"].resetCurrentAttempt();
726 if (this.inMultimove) this.cancelCurrentMultimove();
728 this.moves.length > 0 && this.moves[0].notation == "..."
731 while (this.cursor >= minCursor) this.undo(null, null, "light");
732 this.lastMove = (minCursor == 1 ? this.moves[0] : null);
733 this.incheck = this.vr.getCheckSquares();
734 this.emitFenIfAnalyze();
736 gotoEnd: function() {
737 if (this.cursor == this.moves.length - 1) return;
738 this.gotoMove(this.moves.length - 1);
741 if (this.$refs["board"].choices.length > 0) return;
742 this.orientation = V.GetOppCol(this.orientation);
748 <style lang="sass" scoped>
749 [type="checkbox"]#modalEog+div .card
763 display: inline-block
777 background-color: #FACF8C
782 @media screen and (max-width: 767px)
791 // TODO: later, maybe, allow movesList of variable width
792 // or e.g. between 250 and 350px (but more complicated)
798 @media screen and (max-width: 767px)