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"
26 #turnIndicator(v-if="showTurn") {{ turn }}
27 #controls.button-group
28 button(@click="gotoBegin()")
29 img.inline(src="/images/icons/fast-forward_rev.svg")
30 button(@click="undo()")
31 img.inline(src="/images/icons/play_rev.svg")
32 button(v-if="canFlip" @click="flip()")
33 img.inline(src="/images/icons/flip.svg")
35 @click="runAutoplay()"
36 :class="{'in-autoplay': autoplay}"
38 img.inline(src="/images/icons/autoplay.svg")
39 button(@click="play()")
40 img.inline(src="/images/icons/play.svg")
41 button(@click="gotoEnd()")
42 img.inline(src="/images/icons/fast-forward.svg")
43 p#fenAnalyze(v-show="showFen") {{ (!!vr ? vr.getFen() : "") }}
47 :canAnalyze="canAnalyze"
48 :canDownload="allowDownloadPGN"
50 :message="game.scoreMsg"
51 :firstNum="firstMoveNumber"
56 @showrules="showRules"
57 @analyze="toggleAnalyze"
59 @redraw-board="redrawBoard"
65 import Board from "@/components/Board.vue";
66 import MoveList from "@/components/MoveList.vue";
67 import params from "@/parameters";
68 import { store } from "@/store";
69 import { getSquareId } from "@/utils/squareId";
70 import { getDate } from "@/utils/datetime";
71 import { processModalClick } from "@/utils/modalClick";
72 import { getScoreMessage } from "@/utils/scoring";
73 import { getFullNotation } from "@/utils/notation";
74 import { undoMove } from "@/utils/playUndo";
85 // NOTE: all following variables must be reset at the beginning of a game
86 vr: null, //VariantRules object, game state
91 score: "*", //'*' means 'unfinished'
93 cursor: -1, //index of the move just played
96 firstMoveNumber: 0, //for printing
97 incheck: [], //for Board
106 if (!this.vr) return "";
107 if (this.vr.showMoves != "all") {
109 (this.vr.turn == 'w' ? "White" : "Black") + " to move"];
111 // Cannot flip (racing king or circular chess), or Monochrome
113 this.vr.movesCount == 0 && this.game.mycolor == "w"
114 ? this.st.tr["It's your turn!"]
118 showFen: function() {
120 this.mode == "analyze" &&
121 this.$router.currentRoute.path.indexOf("/analyse") === -1
124 // TODO: is it OK to pass "computed" as properties?
125 // Also, some are seemingly not recomputed when vr is initialized.
126 showMoves: function() {
128 !!this.game.score && this.game.score != "*"
130 : (!!this.vr ? this.vr.showMoves : "none")
133 showTurn: function() {
135 !!this.game.score && this.game.score == '*' &&
138 this.vr.showMoves != "all" ||
140 this.vr.showFirstTurn
144 canAnalyze: function() {
146 (!this.game.mode || this.game.mode != "analyze") &&
147 !!this.vr && this.vr.canAnalyze
150 canFlip: function() {
151 return !!this.vr && this.vr.canFlip;
153 allowDownloadPGN: function() {
155 (!!this.game.score && this.game.score != "*") ||
156 (!!this.vr && !this.vr.someHiddenMoves)
160 created: function() {
161 if (!!this.game.fenStart) this.re_setVariables();
163 mounted: function() {
164 if (!("ontouchstart" in window)) {
166 const baseGameDiv = document.getElementById("baseGame");
167 baseGameDiv.tabIndex = 0;
168 baseGameDiv.addEventListener("click", this.focusBg);
169 baseGameDiv.addEventListener("keydown", this.handleKeys);
170 if (this.st.settings.scrollmove)
171 baseGameDiv.addEventListener("wheel", this.handleScroll);
173 document.getElementById("eogDiv")
174 .addEventListener("click", processModalClick);
176 beforeDestroy: function() {
177 // TODO: probably not required
178 this.autoplay = false;
181 focusBg: function() {
182 document.getElementById("baseGame").focus();
184 handleKeys: function(e) {
185 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
204 handleScroll: function(e) {
206 if (e.deltaY < 0) this.undo();
207 else if (e.deltaY > 0) this.play();
209 redrawBoard: function() {
210 this.$refs["board"].re_setDrawings();
212 showRules: function() {
213 // The button is here only on Game page:
214 document.getElementById("modalRules").checked = true;
216 re_setVariables: function(game) {
217 if (!game) game = this.game; //in case of...
218 this.endgameMessage = "";
219 // "w": default orientation for observed games
220 this.orientation = game.mycolor || "w";
221 this.mode = game.mode || game.type; //TODO: merge...
222 this.moves = JSON.parse(JSON.stringify(game.moves || []));
223 // Post-processing: decorate each move with notation and FEN
224 this.vr = new V(game.fenStart);
225 this.inMultimove = false; //in case of
226 if (!!this.$refs["board"])
228 this.$refs["board"].resetCurrentAttempt();
229 let analyseBtn = document.getElementById("analyzeBtn");
230 if (!!analyseBtn) analyseBtn.classList.remove("active");
231 const parsedFen = V.ParseFen(game.fenStart);
232 const firstMoveColor = parsedFen.turn;
233 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2) + 1;
234 let L = this.moves.length;
235 this.moves.forEach((move,idx) => {
236 // Strategy working also for multi-moves:
237 if (!Array.isArray(move)) move = [move];
239 m.notation = this.vr.getNotation(m);
240 m.unambiguous = V.GetUnambiguousNotation(m);
243 const Lm = move.length;
244 move[Lm - 1].fen = this.vr.getFen();
245 if (idx < L - 1 && this.vr.getCheckSquares().length > 0)
246 move[Lm - 1].notation += "+";
248 this.incheck = this.vr.getCheckSquares();
249 this.score = this.vr.getCurrentScore();
252 !Array.isArray(this.moves[L - 1])
253 ? [this.moves[L - 1]]
255 const Lm = move.length;
256 if (["1-0", "0-1"].includes(this.score)) move[Lm - 1].notation += "#";
257 else if (this.incheck.length > 0) move[Lm - 1].notation += "+";
259 if (this.score != '*') {
260 // Show score on screen
261 const message = getScoreMessage(this.score);
262 this.showEndgameMsg(this.score + " . " + this.st.tr[message]);
264 if (firstMoveColor == "b") {
265 // 'start' & 'end' is required for Board component
269 start: { x: -1, y: -1 },
270 end: { x: -1, y: -1 },
275 this.positionCursorTo(L - 1);
277 positionCursorTo: function(index) {
279 // Note: last move in moves array might be a multi-move
280 if (index >= 0) this.lastMove = this.moves[index];
281 else this.lastMove = null;
283 toggleAnalyze: function() {
284 // Freeze while choices are shown (and autoplay has priority)
287 this.$refs["board"].choices.length > 0 ||
292 if (this.mode != "analyze") {
293 // Enter analyze mode:
294 this.gameMode = this.mode; //was not 'analyze'
295 this.mode = "analyze";
296 if (this.inMultimove) this.cancelCurrentMultimove();
297 this.gameCursor = this.cursor;
298 this.gameMoves = JSON.parse(JSON.stringify(this.moves));
299 document.getElementById("analyzeBtn").classList.add("active");
302 // Exit analyze mode:
303 this.mode = this.gameMode;
304 this.cursor = this.gameCursor;
305 this.moves = this.gameMoves;
306 let fen = this.game.fenStart;
307 if (this.cursor >= 0) {
308 let mv = this.moves[this.cursor];
309 if (!Array.isArray(mv)) mv = [mv];
310 fen = mv[mv.length-1].fen;
312 this.vr = new V(fen);
313 this.inMultimove = false; //in case of
314 this.$refs["board"].resetCurrentAttempt(); //also in case of
315 this.incheck = this.vr.getCheckSquares();
316 if (this.cursor >= 0) this.lastMove = this.moves[this.cursor];
317 else this.lastMove = null;
318 document.getElementById("analyzeBtn").classList.remove("active");
321 download: function() {
322 const content = this.getPgn();
323 // Prepare and trigger download link
324 let downloadAnchor = document.getElementById("download");
325 downloadAnchor.setAttribute("download", "game.pgn");
326 downloadAnchor.href =
327 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
328 downloadAnchor.click();
332 pgn += '[Site "vchess.club"]\n';
333 pgn += '[Variant "' + this.game.vname + '"]\n';
334 const gdt = getDate(new Date(this.game.created || Date.now()));
335 pgn += '[Date "' + gdt + '"]\n';
336 pgn += '[White "' + this.game.players[0].name + '"]\n';
337 pgn += '[Black "' + this.game.players[1].name + '"]\n';
338 pgn += '[Fen "' + this.game.fenStart + '"]\n';
339 pgn += '[Result "' + this.game.score + '"]\n';
341 pgn += '[Url "' + params.serverUrl + '/game/' + this.game.id + '"]\n';
342 if (!!this.game.cadence)
343 pgn += '[Cadence "' + this.game.cadence + '"]\n';
344 pgn += '[Options "' + JSON.stringify(this.game.options) + '"]\n';
346 for (let i = 0; i < this.moves.length; i += 2) {
347 if (i > 0) pgn += " ";
348 // Adjust dots notation for a better display:
349 let fullNotation = getFullNotation(this.moves[i]);
350 if (fullNotation == "...") fullNotation = "..";
351 pgn += (i / 2 + this.firstMoveNumber) + "." + fullNotation;
352 if (i+1 < this.moves.length)
353 pgn += " " + getFullNotation(this.moves[i+1]);
356 for (let i = 0; i < this.moves.length; i += 2) {
357 const moveNumber = i / 2 + this.firstMoveNumber;
358 // Skip "dots move", useless for machine reading:
359 if (this.moves[i].notation != "...") {
360 pgn += moveNumber + ".w " +
361 getFullNotation(this.moves[i], "unambiguous") + "\n";
363 if (i+1 < this.moves.length) {
364 pgn += moveNumber + ".b " +
365 getFullNotation(this.moves[i+1], "unambiguous") + "\n";
370 showEndgameMsg: function(message) {
371 this.endgameMessage = message;
372 document.getElementById("modalEog").checked = true;
374 runAutoplay: function() {
376 this.autoplay = false;
377 if (this.stackToPlay.length > 0)
378 // Move(s) arrived in-between
379 this.play(this.stackToPlay.pop(), "received");
381 else if (this.cursor < this.moves.length - 1) {
382 this.autoplay = true;
383 this.play(null, null, null, "autoplay");
386 // Animate an elementary move
387 animateMove: function(move, callback) {
388 let startSquare = document.getElementById(getSquareId(move.start));
389 if (!startSquare) return; //shouldn't happen but...
390 let endSquare = document.getElementById(getSquareId(move.end));
391 let rectStart = startSquare.getBoundingClientRect();
392 let rectEnd = endSquare.getBoundingClientRect();
394 x: rectEnd.x - rectStart.x,
395 y: rectEnd.y - rectStart.y
397 let movingPiece = document.querySelector(
398 "#" + getSquareId(move.start) + " > img.piece"
400 // For some unknown reasons Opera get "movingPiece == null" error
401 // TODO: is it calling 'animate()' twice ? One extra time ?
402 if (!movingPiece) return;
403 const squares = document.getElementsByClassName("board");
404 for (let i = 0; i < squares.length; i++) {
405 let square = squares.item(i);
406 if (square.id != getSquareId(move.start))
407 // HACK for animation:
408 // (with positive translate, image slides "under background")
409 square.style.zIndex = "-1";
411 movingPiece.style.transform =
412 "translate(" + translation.x + "px," + translation.y + "px)";
413 movingPiece.style.transitionDuration = "0.25s";
414 movingPiece.style.zIndex = "3000";
416 for (let i = 0; i < squares.length; i++)
417 squares.item(i).style.zIndex = "auto";
418 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
423 emitFenIfAnalyze: function() {
424 if (this.game.mode == "analyze") {
425 let fen = this.game.fenStart;
426 if (!!this.lastMove) {
427 if (Array.isArray(this.lastMove)) {
428 const L = this.lastMove.length;
429 fen = this.lastMove[L-1].fen;
431 else fen = this.lastMove.fen;
433 this.$emit("fenchange", fen);
436 clickSquare: function(square) {
437 // Some variants make use of a single click at specific times:
438 const move_s = this.vr.doClick(square);
440 const playMove = () => {
441 if (!Array.isArray(move_s)) this.play(move_s);
442 else this.$refs["board"].choices = move_s;
444 if ("ontouchstart" in window) {
445 const squareId = "sq-" + square[0] + "-" + square[1];
446 const highlight = function(on, sq) {
447 let elt = document.getElementById(sq);
449 if (on) elt.classList.add("touch-hover");
450 else elt.classList.remove("touch-hover");
453 // Touch screen (smartphone): require confirmation
454 const squareStr = square[0] + "_" + square[1]
455 if (this.touchLastClick == squareId) {
456 highlight(false, squareId);
460 highlight(true, squareId);
461 highlight(false, this.touchLastClick);
463 this.touchLastClick = squareId;
468 // "light": if gotoMove() or gotoEnd()
469 play: function(move, received, light, autoplay) {
470 // Freeze while choices are shown:
472 !!this.$refs["board"].selectedPiece ||
473 this.$refs["board"].choices.length > 0
477 const navigate = !move;
478 // Forbid navigation during autoplay:
479 if (navigate && this.autoplay && !autoplay) return;
480 // Forbid playing outside analyze mode, except if move is received.
481 // Sufficient condition because Board already knows which turn it is.
483 this.mode != "analyze" &&
486 (this.game.score != "*" || this.cursor < this.moves.length - 1)
491 if (this.autoplay || this.inPlay) {
492 // Received moves while autoplaying are stacked,
493 // and in observed games they could arrive too fast:
494 this.stackToPlay.unshift(move);
497 if (this.mode == "analyze") this.toggleAnalyze();
498 if (this.cursor < this.moves.length - 1)
499 // To play a received move, cursor must be at the end of the game:
503 // The board may show some possible moves: (TODO: bad solution)
504 this.$refs["board"].resetCurrentAttempt();
505 const playSubmove = (smove) => {
506 smove.notation = this.vr.getNotation(smove);
507 smove.unambiguous = V.GetUnambiguousNotation(smove);
509 if (this.inMultimove && !!this.lastMove) {
510 if (!Array.isArray(this.lastMove))
511 this.lastMove = [this.lastMove, smove];
512 else this.lastMove.push(smove);
514 if (!this.inMultimove) {
516 this.lastMove = smove;
517 // Condition is "!navigate" but we mean "!this.autoplay"
519 if (this.cursor < this.moves.length - 1)
520 this.moves = this.moves.slice(0, this.cursor + 1);
521 this.moves.push(smove);
523 this.inMultimove = true; //potentially
526 else if (!navigate) {
527 // Already in the middle of a multi-move
528 const L = this.moves.length;
529 if (!Array.isArray(this.moves[L-1]))
530 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
531 else this.moves[L-1].push(smove);
534 const playMove = () => {
536 ["all", "highlight"].includes(V.ShowMoves) &&
537 (this.autoplay || !!received)
539 if (!Array.isArray(move)) move = [move];
542 const initurn = this.vr.turn;
543 (function executeMove() {
544 const smove = move[moveIdx++];
545 // NOTE: condition "smove.start.x >= 0" required for Dynamo,
546 // because second move may be empty. noHighlight condition
547 // is used at least for Chakart.
548 if (animate && smove.start.x >= 0 && !smove.end.noHighlight) {
549 self.animateMove(smove, () => {
551 if (moveIdx < move.length) setTimeout(executeMove, 500);
552 else afterMove(smove, initurn);
557 if (moveIdx < move.length) executeMove();
558 else afterMove(smove, initurn);
562 const computeScore = () => {
563 const score = this.vr.getCurrentScore();
565 if (["1-0", "0-1"].includes(score)) {
566 if (Array.isArray(this.lastMove)) {
567 const L = this.lastMove.length;
568 this.lastMove[L - 1].notation += "#";
570 else this.lastMove.notation += "#";
573 if (score != "*" && ["analyze", "versus"].includes(this.mode)) {
574 const message = getScoreMessage(score, V.ReverseColors);
575 // Show score on screen
576 this.showEndgameMsg(score + " . " + this.st.tr[message]);
580 const afterMove = (smove, initurn) => {
581 if (this.vr.turn != initurn) {
582 // Turn has changed: move is complete
584 // NOTE: only FEN of last sub-move is required (=> setting it here)
585 smove.fen = this.vr.getFen();
586 this.emitFenIfAnalyze();
587 this.inMultimove = false;
588 this.incheck = this.vr.getCheckSquares();
589 if (this.incheck.length > 0) smove.notation += "+";
590 this.score = computeScore();
592 if (this.cursor < this.moves.length - 1)
593 setTimeout(() => this.play(null, null, null, "autoplay"), 1000);
595 this.autoplay = false;
596 if (this.stackToPlay.length > 0)
597 // Move(s) arrived in-between
598 this.play(this.stackToPlay.pop(), "received");
601 if (this.mode != "analyze" && !navigate) {
603 // Post-processing (e.g. computer play).
604 const L = this.moves.length;
605 // NOTE: always emit the score, even in unfinished
606 this.$emit("newmove", this.moves[L-1], { score: this.score });
610 if (this.stackToPlay.length > 0)
611 // Move(s) arrived in-between
612 this.play(this.stackToPlay.pop(), "received");
617 // NOTE: navigate and received are mutually exclusive
619 // The move to navigate to is necessarily full:
620 if (this.cursor == this.moves.length - 1) return; //no more moves
621 move = this.moves[this.cursor + 1];
622 if (!this.autoplay) {
623 // Just play the move:
624 if (!Array.isArray(move)) move = [move];
625 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
627 this.lastMove = move;
628 this.incheck = this.vr.getCheckSquares();
629 this.score = computeScore();
630 this.emitFenIfAnalyze();
638 cancelCurrentMultimove: function() {
639 const L = this.moves.length;
640 let move = this.moves[L-1];
641 if (!Array.isArray(move)) move = [move];
642 for (let i = move.length - 1; i >= 0; i--) this.vr.undo(move[i]);
645 this.inMultimove = false;
647 cancelLastMove: function() {
648 // The last played move was canceled (corr game)
652 // "light": if gotoMove() or gotoBegin()
653 undo: function(move, light) {
656 !!this.$refs["board"].selectedPiece ||
657 this.$refs["board"].choices.length > 0
661 this.$refs["board"].resetCurrentAttempt();
662 if (this.inMultimove) {
663 this.cancelCurrentMultimove();
664 this.incheck = this.vr.getCheckSquares();
665 if (this.cursor >= 0) this.lastMove = this.moves[this.cursor];
666 else this.lastMove = null;
671 this.moves.length > 0 && this.moves[0].notation == "..."
674 if (this.cursor < minCursor) return; //no more moves
675 move = this.moves[this.cursor];
677 this.$refs["board"].resetCurrentAttempt();
678 undoMove(move, this.vr);
679 if (light) this.cursor--;
681 this.positionCursorTo(this.cursor - 1);
682 this.incheck = this.vr.getCheckSquares();
683 this.emitFenIfAnalyze();
687 gotoMove: function(index) {
690 !!this.$refs["board"].selectedPiece ||
691 this.$refs["board"].choices.length > 0
695 this.$refs["board"].resetCurrentAttempt();
696 if (this.inMultimove) this.cancelCurrentMultimove();
697 if (index == this.cursor) return;
698 if (index < this.cursor) {
699 while (this.cursor > index)
700 this.undo(null, null, "light");
703 // index > this.cursor)
704 while (this.cursor < index)
705 this.play(null, null, "light");
707 // NOTE: next line also re-assign cursor, but it's very light
708 this.positionCursorTo(index);
709 this.incheck = this.vr.getCheckSquares();
710 this.emitFenIfAnalyze();
712 gotoBegin: function() {
715 !!this.$refs["board"].selectedPiece ||
716 this.$refs["board"].choices.length > 0
720 this.$refs["board"].resetCurrentAttempt();
721 if (this.inMultimove) this.cancelCurrentMultimove();
723 this.moves.length > 0 && this.moves[0].notation == "..."
726 while (this.cursor >= minCursor) this.undo(null, null, "light");
727 this.lastMove = (minCursor == 1 ? this.moves[0] : null);
728 this.incheck = this.vr.getCheckSquares();
729 this.emitFenIfAnalyze();
731 gotoEnd: function() {
732 if (this.cursor == this.moves.length - 1) return;
733 this.gotoMove(this.moves.length - 1);
736 if (this.$refs["board"].choices.length > 0) return;
737 this.orientation = V.GetOppCol(this.orientation);
743 <style lang="sass" scoped>
744 [type="checkbox"]#modalEog+div .card
758 display: inline-block
772 background-color: #FACF8C
777 @media screen and (max-width: 767px)
786 // TODO: later, maybe, allow movesList of variable width
787 // or e.g. between 250 and 350px (but more complicated)
793 @media screen and (max-width: 767px)