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"
55 @showrules="showRules"
56 @analyze="toggleAnalyze"
58 @redraw-board="redrawBoard"
64 import Board from "@/components/Board.vue";
65 import MoveList from "@/components/MoveList.vue";
66 import params from "@/parameters";
67 import { store } from "@/store";
68 import { getSquareId } from "@/utils/squareId";
69 import { getDate } from "@/utils/datetime";
70 import { processModalClick } from "@/utils/modalClick";
71 import { getScoreMessage } from "@/utils/scoring";
72 import { getFullNotation } from "@/utils/notation";
73 import { undoMove } from "@/utils/playUndo";
84 // NOTE: all following variables must be reset at the beginning of a game
85 vr: null, //VariantRules object, game state
89 score: "*", //'*' means 'unfinished'
91 cursor: -1, //index of the move just played
93 firstMoveNumber: 0, //for printing
94 incheck: [], //for Board
103 if (!this.vr) return "";
104 if (this.vr.showMoves != "all") {
106 (this.vr.turn == 'w' ? "White" : "Black") + " to move"];
108 // Cannot flip (racing king or circular chess), or Monochrome
110 this.vr.movesCount == 0 && this.game.mycolor == "w"
111 ? this.st.tr["It's your turn!"]
115 showFen: function() {
117 this.mode == "analyze" &&
118 this.$router.currentRoute.path.indexOf("/analyse") === -1
121 // TODO: is it OK to pass "computed" as properties?
122 // Also, some are seemingly not recomputed when vr is initialized.
123 showMoves: function() {
125 !!this.game.score && this.game.score != "*"
127 : (!!this.vr ? this.vr.showMoves : "none")
130 showTurn: function() {
132 !!this.game.score && this.game.score == '*' &&
135 this.vr.showMoves != "all" ||
137 this.vr.showFirstTurn
141 canAnalyze: function() {
143 !!this.game.mode && this.game.mode != "analyze" &&
144 !!this.vr && this.vr.canAnalyze
147 canFlip: function() {
148 return !!this.vr && this.vr.canFlip;
150 allowDownloadPGN: function() {
152 (!!this.game.score && this.game.score != "*") ||
153 (!!this.vr && !this.vr.someHiddenMoves)
157 created: function() {
158 if (!!this.game.fenStart) this.re_setVariables();
160 mounted: function() {
161 if (!("ontouchstart" in window)) {
163 const baseGameDiv = document.getElementById("baseGame");
164 baseGameDiv.tabIndex = 0;
165 baseGameDiv.addEventListener("click", this.focusBg);
166 baseGameDiv.addEventListener("keydown", this.handleKeys);
167 baseGameDiv.addEventListener("wheel", this.handleScroll);
169 document.getElementById("eogDiv")
170 .addEventListener("click", processModalClick);
172 beforeDestroy: function() {
173 // TODO: probably not required
174 this.autoplay = false;
177 focusBg: function() {
178 document.getElementById("baseGame").focus();
180 handleKeys: function(e) {
181 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
200 handleScroll: function(e) {
202 if (e.deltaY < 0) this.undo();
203 else if (e.deltaY > 0) this.play();
205 redrawBoard: function() {
206 this.$refs["board"].re_setDrawings();
208 showRules: function() {
209 // The button is here only on Game page:
210 document.getElementById("modalRules").checked = true;
212 re_setVariables: function(game) {
213 if (!game) game = this.game; //in case of...
214 this.endgameMessage = "";
215 // "w": default orientation for observed games
216 this.orientation = game.mycolor || "w";
217 this.mode = game.mode || game.type; //TODO: merge...
218 this.moves = JSON.parse(JSON.stringify(game.moves || []));
219 // Post-processing: decorate each move with notation and FEN
220 this.vr = new V(game.fenStart);
221 this.inMultimove = false; //in case of
222 if (!!this.$refs["board"])
224 this.$refs["board"].resetCurrentAttempt();
225 let analyseBtn = document.getElementById("analyzeBtn");
226 if (!!analyseBtn) analyseBtn.classList.remove("active");
227 const parsedFen = V.ParseFen(game.fenStart);
228 const firstMoveColor = parsedFen.turn;
229 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2) + 1;
230 let L = this.moves.length;
232 // Could be started on a random position in analysis mode:
233 this.incheck = this.vr.getCheckSquares();
234 this.score = this.vr.getCurrentScore();
235 if (this.score != '*') {
236 // Show score on screen
237 const message = getScoreMessage(this.score);
238 this.showEndgameMsg(this.score + " . " + this.st.tr[message]);
242 this.moves.forEach((move,idx) => {
243 // Strategy working also for multi-moves:
244 if (!Array.isArray(move)) move = [move];
245 const Lm = move.length;
246 move.forEach((m,idxM) => {
247 m.notation = this.vr.getNotation(m);
248 m.unambiguous = V.GetUnambiguousNotation(m);
250 const checkSquares = this.vr.getCheckSquares();
251 if (checkSquares.length > 0) m.notation += "+";
252 if (idxM == Lm - 1) m.fen = this.vr.getFen();
253 if (idx == L - 1 && idxM == Lm - 1) {
254 this.incheck = checkSquares;
255 this.score = this.vr.getCurrentScore();
256 if (["1-0", "0-1"].includes(this.score)) m.notation += "#";
261 if (firstMoveColor == "b") {
262 // 'start' & 'end' is required for Board component
266 start: { x: -1, y: -1 },
267 end: { x: -1, y: -1 },
272 this.positionCursorTo(L - 1);
274 positionCursorTo: function(index) {
276 // Note: last move in moves array might be a multi-move
277 if (index >= 0) this.lastMove = this.moves[index];
278 else this.lastMove = null;
280 toggleAnalyze: function() {
281 // Freeze while choices are shown (and autoplay has priority)
284 this.$refs["board"].choices.length > 0 ||
289 if (this.mode != "analyze") {
290 // Enter analyze mode:
291 this.mode = "analyze";
292 if (this.inMultimove) this.cancelCurrentMultimove();
293 this.gameMode = this.mode; //was not 'analyze'
294 this.gameCursor = this.cursor;
295 this.gameMoves = JSON.parse(JSON.stringify(this.moves));
296 document.getElementById("analyzeBtn").classList.add("active");
299 // Exit analyze mode:
300 this.mode = this.gameMode ;
301 this.cursor = this.gameCursor;
302 this.moves = this.gameMoves;
303 let fen = this.game.fenStart;
304 if (this.cursor >= 0) {
305 let mv = this.moves[this.cursor];
306 if (!Array.isArray(mv)) mv = [mv];
307 fen = mv[mv.length-1].fen;
309 this.vr = new V(fen);
310 this.inMultimove = false; //in case of
311 this.$refs["board"].resetCurrentAttempt(); //also in case of
312 this.incheck = this.vr.getCheckSquares();
313 if (this.cursor >= 0) this.lastMove = this.moves[this.cursor];
314 else this.lastMove = null;
315 document.getElementById("analyzeBtn").classList.remove("active");
318 download: function() {
319 const content = this.getPgn();
320 // Prepare and trigger download link
321 let downloadAnchor = document.getElementById("download");
322 downloadAnchor.setAttribute("download", "game.pgn");
323 downloadAnchor.href =
324 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
325 downloadAnchor.click();
329 pgn += '[Site "vchess.club"]\n';
330 pgn += '[Variant "' + this.game.vname + '"]\n';
331 const gdt = getDate(new Date(this.game.created || Date.now()));
332 pgn += '[Date "' + gdt + '"]\n';
333 pgn += '[White "' + this.game.players[0].name + '"]\n';
334 pgn += '[Black "' + this.game.players[1].name + '"]\n';
335 pgn += '[Fen "' + this.game.fenStart + '"]\n';
336 pgn += '[Result "' + this.game.score + '"]\n';
338 pgn += '[Url "' + params.serverUrl + '/game/' + this.game.id + '"]\n';
339 if (!!this.game.cadence)
340 pgn += '[Cadence "' + this.game.cadence + '"]\n';
342 for (let i = 0; i < this.moves.length; i += 2) {
343 if (i > 0) pgn += " ";
344 // Adjust dots notation for a better display:
345 let fullNotation = getFullNotation(this.moves[i]);
346 if (fullNotation == "...") fullNotation = "..";
347 pgn += (i / 2 + this.firstMoveNumber) + "." + fullNotation;
348 if (i+1 < this.moves.length)
349 pgn += " " + getFullNotation(this.moves[i+1]);
352 for (let i = 0; i < this.moves.length; i += 2) {
353 const moveNumber = i / 2 + this.firstMoveNumber;
354 // Skip "dots move", useless for machine reading:
355 if (this.moves[i].notation != "...") {
356 pgn += moveNumber + ".w " +
357 getFullNotation(this.moves[i], "unambiguous") + "\n";
359 if (i+1 < this.moves.length) {
360 pgn += moveNumber + ".b " +
361 getFullNotation(this.moves[i+1], "unambiguous") + "\n";
366 showEndgameMsg: function(message) {
367 this.endgameMessage = message;
368 document.getElementById("modalEog").checked = true;
370 runAutoplay: function() {
372 this.autoplay = false;
373 if (this.stackToPlay.length > 0)
374 // Move(s) arrived in-between
375 this.play(this.stackToPlay.pop(), "received");
377 else if (this.cursor < this.moves.length - 1) {
378 this.autoplay = true;
379 this.play(null, null, null, "autoplay");
382 // Animate an elementary move
383 animateMove: function(move, callback) {
384 let startSquare = document.getElementById(getSquareId(move.start));
385 if (!startSquare) return; //shouldn't happen but...
386 let endSquare = document.getElementById(getSquareId(move.end));
387 let rectStart = startSquare.getBoundingClientRect();
388 let rectEnd = endSquare.getBoundingClientRect();
390 x: rectEnd.x - rectStart.x,
391 y: rectEnd.y - rectStart.y
393 let movingPiece = document.querySelector(
394 "#" + getSquareId(move.start) + " > img.piece"
396 // For some unknown reasons Opera get "movingPiece == null" error
397 // TODO: is it calling 'animate()' twice ? One extra time ?
398 if (!movingPiece) return;
399 const squares = document.getElementsByClassName("board");
400 for (let i = 0; i < squares.length; i++) {
401 let square = squares.item(i);
402 if (square.id != getSquareId(move.start))
403 // HACK for animation:
404 // (with positive translate, image slides "under background")
405 square.style.zIndex = "-1";
407 movingPiece.style.transform =
408 "translate(" + translation.x + "px," + translation.y + "px)";
409 movingPiece.style.transitionDuration = "0.25s";
410 movingPiece.style.zIndex = "3000";
412 for (let i = 0; i < squares.length; i++)
413 squares.item(i).style.zIndex = "auto";
414 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
419 emitFenIfAnalyze: function() {
420 if (this.game.mode == "analyze") {
421 let fen = this.game.fenStart;
422 if (!!this.lastMove) {
423 if (Array.isArray(this.lastMove)) {
424 const L = this.lastMove.length;
425 fen = this.lastMove[L-1].fen;
427 else fen = this.lastMove.fen;
429 this.$emit("fenchange", fen);
432 clickSquare: function(square) {
433 // Some variants make use of a single click at specific times:
434 const move = this.vr.doClick(square);
435 if (!!move) this.play(move);
437 // "light": if gotoMove() or gotoEnd()
438 play: function(move, received, light, autoplay) {
439 // Freeze while choices are shown:
441 !!this.$refs["board"].selectedPiece ||
442 this.$refs["board"].choices.length > 0
446 const navigate = !move;
447 // Forbid navigation during autoplay:
448 if (navigate && this.autoplay && !autoplay) return;
449 // Forbid playing outside analyze mode, except if move is received.
450 // Sufficient condition because Board already knows which turn it is.
452 this.mode != "analyze" &&
455 (this.game.score != "*" || this.cursor < this.moves.length - 1)
460 if (this.autoplay || this.inPlay) {
461 // Received moves while autoplaying are stacked,
462 // and in observed games they could arrive too fast:
463 this.stackToPlay.unshift(move);
467 if (this.mode == "analyze") this.toggleAnalyze();
468 if (this.cursor < this.moves.length - 1)
469 // To play a received move, cursor must be at the end of the game:
472 // The board may show some possible moves: (TODO: bad solution)
473 this.$refs["board"].resetCurrentAttempt();
474 const playSubmove = (smove) => {
475 smove.notation = this.vr.getNotation(smove);
476 smove.unambiguous = V.GetUnambiguousNotation(smove);
478 if (this.inMultimove && !!this.lastMove) {
479 if (!Array.isArray(this.lastMove))
480 this.lastMove = [this.lastMove, smove];
481 else this.lastMove.push(smove);
483 // Is opponent (or me) in check?
484 this.incheck = this.vr.getCheckSquares();
485 if (this.incheck.length > 0) smove.notation += "+";
486 if (!this.inMultimove) {
488 this.lastMove = smove;
489 // Condition is "!navigate" but we mean "!this.autoplay"
491 if (this.cursor < this.moves.length - 1)
492 this.moves = this.moves.slice(0, this.cursor + 1);
493 this.moves.push(smove);
495 this.inMultimove = true; //potentially
497 } else if (!navigate) {
498 // Already in the middle of a multi-move
499 const L = this.moves.length;
500 if (!Array.isArray(this.moves[L-1]))
501 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
502 else this.moves[L-1].push(smove);
505 const playMove = () => {
507 ["all", "highlight"].includes(V.ShowMoves) &&
508 (this.autoplay || !!received)
510 if (!Array.isArray(move)) move = [move];
513 const initurn = this.vr.turn;
514 (function executeMove() {
515 const smove = move[moveIdx++];
516 // NOTE: condition "smove.start.x >= 0" required for Dynamo,
517 // because second move may be empty.
518 if (animate && smove.start.x >= 0) {
519 self.animateMove(smove, () => {
521 if (moveIdx < move.length) setTimeout(executeMove, 500);
522 else afterMove(smove, initurn);
526 if (moveIdx < move.length) executeMove();
527 else afterMove(smove, initurn);
531 const computeScore = () => {
532 const score = this.vr.getCurrentScore();
534 if (["1-0", "0-1"].includes(score)) {
535 if (Array.isArray(this.lastMove)) {
536 const L = this.lastMove.length;
537 this.lastMove[L - 1].notation += "#";
539 else this.lastMove.notation += "#";
542 if (score != "*" && ["analyze", "versus"].includes(this.mode)) {
543 const message = getScoreMessage(score);
544 // Show score on screen
545 this.showEndgameMsg(score + " . " + this.st.tr[message]);
549 const afterMove = (smove, initurn) => {
550 if (this.vr.turn != initurn) {
551 // Turn has changed: move is complete
553 // NOTE: only FEN of last sub-move is required (=> setting it here)
554 smove.fen = this.vr.getFen();
555 this.emitFenIfAnalyze();
556 this.inMultimove = false;
557 this.score = computeScore();
559 if (this.cursor < this.moves.length - 1)
560 setTimeout(() => this.play(null, null, null, "autoplay"), 1000);
562 this.autoplay = false;
563 if (this.stackToPlay.length > 0)
564 // Move(s) arrived in-between
565 this.play(this.stackToPlay.pop(), "received");
568 if (this.mode != "analyze" && !navigate) {
570 // Post-processing (e.g. computer play).
571 const L = this.moves.length;
572 // NOTE: always emit the score, even in unfinished
573 this.$emit("newmove", this.moves[L-1], { score: this.score });
576 if (this.stackToPlay.length > 0)
577 // Move(s) arrived in-between
578 this.play(this.stackToPlay.pop(), "received");
583 // NOTE: navigate and received are mutually exclusive
585 // The move to navigate to is necessarily full:
586 if (this.cursor == this.moves.length - 1) return; //no more moves
587 move = this.moves[this.cursor + 1];
588 if (!this.autoplay) {
589 // Just play the move:
590 if (!Array.isArray(move)) move = [move];
591 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
593 this.lastMove = move;
594 this.incheck = this.vr.getCheckSquares();
595 this.score = computeScore();
596 this.emitFenIfAnalyze();
604 cancelCurrentMultimove: function() {
605 const L = this.moves.length;
606 let move = this.moves[L-1];
607 if (!Array.isArray(move)) move = [move];
608 for (let i = move.length - 1; i >= 0; i--) this.vr.undo(move[i]);
611 this.inMultimove = false;
613 cancelLastMove: function() {
614 // The last played move was canceled (corr game)
618 // "light": if gotoMove() or gotoBegin()
619 undo: function(move, light) {
622 !!this.$refs["board"].selectedPiece ||
623 this.$refs["board"].choices.length > 0
627 this.$refs["board"].resetCurrentAttempt();
628 if (this.inMultimove) {
629 this.cancelCurrentMultimove();
630 this.incheck = this.vr.getCheckSquares();
631 if (this.cursor >= 0) this.lastMove = this.moves[this.cursor];
632 else this.lastMove = null;
636 this.moves.length > 0 && this.moves[0].notation == "..."
639 if (this.cursor < minCursor) return; //no more moves
640 move = this.moves[this.cursor];
642 this.$refs["board"].resetCurrentAttempt();
643 undoMove(move, this.vr);
644 if (light) this.cursor--;
646 this.positionCursorTo(this.cursor - 1);
647 this.incheck = this.vr.getCheckSquares();
648 this.emitFenIfAnalyze();
652 gotoMove: function(index) {
655 !!this.$refs["board"].selectedPiece ||
656 this.$refs["board"].choices.length > 0
660 this.$refs["board"].resetCurrentAttempt();
661 if (this.inMultimove) this.cancelCurrentMultimove();
662 if (index == this.cursor) return;
663 if (index < this.cursor) {
664 while (this.cursor > index)
665 this.undo(null, null, "light");
668 // index > this.cursor)
669 while (this.cursor < index)
670 this.play(null, null, "light");
672 // NOTE: next line also re-assign cursor, but it's very light
673 this.positionCursorTo(index);
674 this.incheck = this.vr.getCheckSquares();
675 this.emitFenIfAnalyze();
677 gotoBegin: function() {
680 !!this.$refs["board"].selectedPiece ||
681 this.$refs["board"].choices.length > 0
685 this.$refs["board"].resetCurrentAttempt();
686 if (this.inMultimove) this.cancelCurrentMultimove();
688 this.moves.length > 0 && this.moves[0].notation == "..."
691 while (this.cursor >= minCursor) this.undo(null, null, "light");
692 this.lastMove = (minCursor == 1 ? this.moves[0] : null);
693 this.incheck = this.vr.getCheckSquares();
694 this.emitFenIfAnalyze();
696 gotoEnd: function() {
697 if (this.cursor == this.moves.length - 1) return;
698 this.gotoMove(this.moves.length - 1);
701 if (this.$refs["board"].choices.length > 0) return;
702 this.orientation = V.GetOppCol(this.orientation);
708 <style lang="sass" scoped>
709 [type="checkbox"]#modalEog+div .card
723 display: inline-block
737 background-color: #FACF8C
742 @media screen and (max-width: 767px)
751 // TODO: later, maybe, allow movesList of variable width
752 // or e.g. between 250 and 350px (but more complicated)
758 @media screen and (max-width: 767px)