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
95 firstMoveNumber: 0, //for printing
96 incheck: [], //for Board
105 if (!this.vr) return "";
106 if (this.vr.showMoves != "all") {
108 (this.vr.turn == 'w' ? "White" : "Black") + " to move"];
110 // Cannot flip (racing king or circular chess), or Monochrome
112 this.vr.movesCount == 0 && this.game.mycolor == "w"
113 ? this.st.tr["It's your turn!"]
117 showFen: function() {
119 this.mode == "analyze" &&
120 this.$router.currentRoute.path.indexOf("/analyse") === -1
123 // TODO: is it OK to pass "computed" as properties?
124 // Also, some are seemingly not recomputed when vr is initialized.
125 showMoves: function() {
127 !!this.game.score && this.game.score != "*"
129 : (!!this.vr ? this.vr.showMoves : "none")
132 showTurn: function() {
134 !!this.game.score && this.game.score == '*' &&
137 this.vr.showMoves != "all" ||
139 this.vr.showFirstTurn
143 canAnalyze: function() {
145 (!this.game.mode || this.game.mode != "analyze") &&
146 !!this.vr && this.vr.canAnalyze
149 canFlip: function() {
150 return !!this.vr && this.vr.canFlip;
152 allowDownloadPGN: function() {
154 (!!this.game.score && this.game.score != "*") ||
155 (!!this.vr && !this.vr.someHiddenMoves)
159 created: function() {
160 if (!!this.game.fenStart) this.re_setVariables();
162 mounted: function() {
163 if (!("ontouchstart" in window)) {
165 const baseGameDiv = document.getElementById("baseGame");
166 baseGameDiv.tabIndex = 0;
167 baseGameDiv.addEventListener("click", this.focusBg);
168 baseGameDiv.addEventListener("keydown", this.handleKeys);
169 baseGameDiv.addEventListener("wheel", this.handleScroll);
171 document.getElementById("eogDiv")
172 .addEventListener("click", processModalClick);
174 beforeDestroy: function() {
175 // TODO: probably not required
176 this.autoplay = false;
179 focusBg: function() {
180 document.getElementById("baseGame").focus();
182 handleKeys: function(e) {
183 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
202 handleScroll: function(e) {
204 if (e.deltaY < 0) this.undo();
205 else if (e.deltaY > 0) this.play();
207 redrawBoard: function() {
208 this.$refs["board"].re_setDrawings();
210 showRules: function() {
211 // The button is here only on Game page:
212 document.getElementById("modalRules").checked = true;
214 re_setVariables: function(game) {
215 if (!game) game = this.game; //in case of...
216 this.endgameMessage = "";
217 // "w": default orientation for observed games
218 this.orientation = game.mycolor || "w";
219 this.mode = game.mode || game.type; //TODO: merge...
220 this.moves = JSON.parse(JSON.stringify(game.moves || []));
221 // Post-processing: decorate each move with notation and FEN
222 this.vr = new V(game.fenStart);
223 this.inMultimove = false; //in case of
224 if (!!this.$refs["board"])
226 this.$refs["board"].resetCurrentAttempt();
227 let analyseBtn = document.getElementById("analyzeBtn");
228 if (!!analyseBtn) analyseBtn.classList.remove("active");
229 const parsedFen = V.ParseFen(game.fenStart);
230 const firstMoveColor = parsedFen.turn;
231 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2) + 1;
232 let L = this.moves.length;
233 this.moves.forEach((move,idx) => {
234 // Strategy working also for multi-moves:
235 if (!Array.isArray(move)) move = [move];
237 m.notation = this.vr.getNotation(m);
238 m.unambiguous = V.GetUnambiguousNotation(m);
241 const Lm = move.length;
242 move[Lm - 1].fen = this.vr.getFen();
243 if (idx < L - 1 && this.vr.getCheckSquares().length > 0)
244 move[Lm - 1].notation += "+";
246 this.incheck = this.vr.getCheckSquares();
247 this.score = this.vr.getCurrentScore();
250 !Array.isArray(this.moves[L - 1])
251 ? [this.moves[L - 1]]
253 const Lm = move.length;
254 if (["1-0", "0-1"].includes(this.score)) move[Lm - 1].notation += "#";
255 else if (this.incheck.length > 0) move[Lm - 1].notation += "+";
257 if (this.score != '*') {
258 // Show score on screen
259 const message = getScoreMessage(this.score);
260 this.showEndgameMsg(this.score + " . " + this.st.tr[message]);
262 if (firstMoveColor == "b") {
263 // 'start' & 'end' is required for Board component
267 start: { x: -1, y: -1 },
268 end: { x: -1, y: -1 },
273 this.positionCursorTo(L - 1);
275 positionCursorTo: function(index) {
277 // Note: last move in moves array might be a multi-move
278 if (index >= 0) this.lastMove = this.moves[index];
279 else this.lastMove = null;
281 toggleAnalyze: function() {
282 // Freeze while choices are shown (and autoplay has priority)
285 this.$refs["board"].choices.length > 0 ||
290 if (this.mode != "analyze") {
291 // Enter analyze mode:
292 this.gameMode = this.mode; //was not 'analyze'
293 this.mode = "analyze";
294 if (this.inMultimove) this.cancelCurrentMultimove();
295 this.gameCursor = this.cursor;
296 this.gameMoves = JSON.parse(JSON.stringify(this.moves));
297 document.getElementById("analyzeBtn").classList.add("active");
300 // Exit analyze mode:
301 this.mode = this.gameMode;
302 this.cursor = this.gameCursor;
303 this.moves = this.gameMoves;
304 let fen = this.game.fenStart;
305 if (this.cursor >= 0) {
306 let mv = this.moves[this.cursor];
307 if (!Array.isArray(mv)) mv = [mv];
308 fen = mv[mv.length-1].fen;
310 this.vr = new V(fen);
311 this.inMultimove = false; //in case of
312 this.$refs["board"].resetCurrentAttempt(); //also in case of
313 this.incheck = this.vr.getCheckSquares();
314 if (this.cursor >= 0) this.lastMove = this.moves[this.cursor];
315 else this.lastMove = null;
316 document.getElementById("analyzeBtn").classList.remove("active");
319 download: function() {
320 const content = this.getPgn();
321 // Prepare and trigger download link
322 let downloadAnchor = document.getElementById("download");
323 downloadAnchor.setAttribute("download", "game.pgn");
324 downloadAnchor.href =
325 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
326 downloadAnchor.click();
330 pgn += '[Site "vchess.club"]\n';
331 pgn += '[Variant "' + this.game.vname + '"]\n';
332 const gdt = getDate(new Date(this.game.created || Date.now()));
333 pgn += '[Date "' + gdt + '"]\n';
334 pgn += '[White "' + this.game.players[0].name + '"]\n';
335 pgn += '[Black "' + this.game.players[1].name + '"]\n';
336 pgn += '[Fen "' + this.game.fenStart + '"]\n';
337 pgn += '[Result "' + this.game.score + '"]\n';
339 pgn += '[Url "' + params.serverUrl + '/game/' + this.game.id + '"]\n';
340 if (!!this.game.cadence)
341 pgn += '[Cadence "' + this.game.cadence + '"]\n';
343 for (let i = 0; i < this.moves.length; i += 2) {
344 if (i > 0) pgn += " ";
345 // Adjust dots notation for a better display:
346 let fullNotation = getFullNotation(this.moves[i]);
347 if (fullNotation == "...") fullNotation = "..";
348 pgn += (i / 2 + this.firstMoveNumber) + "." + fullNotation;
349 if (i+1 < this.moves.length)
350 pgn += " " + getFullNotation(this.moves[i+1]);
353 for (let i = 0; i < this.moves.length; i += 2) {
354 const moveNumber = i / 2 + this.firstMoveNumber;
355 // Skip "dots move", useless for machine reading:
356 if (this.moves[i].notation != "...") {
357 pgn += moveNumber + ".w " +
358 getFullNotation(this.moves[i], "unambiguous") + "\n";
360 if (i+1 < this.moves.length) {
361 pgn += moveNumber + ".b " +
362 getFullNotation(this.moves[i+1], "unambiguous") + "\n";
367 showEndgameMsg: function(message) {
368 this.endgameMessage = message;
369 document.getElementById("modalEog").checked = true;
371 runAutoplay: function() {
373 this.autoplay = false;
374 if (this.stackToPlay.length > 0)
375 // Move(s) arrived in-between
376 this.play(this.stackToPlay.pop(), "received");
378 else if (this.cursor < this.moves.length - 1) {
379 this.autoplay = true;
380 this.play(null, null, null, "autoplay");
383 // Animate an elementary move
384 animateMove: function(move, callback) {
385 let startSquare = document.getElementById(getSquareId(move.start));
386 if (!startSquare) return; //shouldn't happen but...
387 let endSquare = document.getElementById(getSquareId(move.end));
388 let rectStart = startSquare.getBoundingClientRect();
389 let rectEnd = endSquare.getBoundingClientRect();
391 x: rectEnd.x - rectStart.x,
392 y: rectEnd.y - rectStart.y
394 let movingPiece = document.querySelector(
395 "#" + getSquareId(move.start) + " > img.piece"
397 // For some unknown reasons Opera get "movingPiece == null" error
398 // TODO: is it calling 'animate()' twice ? One extra time ?
399 if (!movingPiece) return;
400 const squares = document.getElementsByClassName("board");
401 for (let i = 0; i < squares.length; i++) {
402 let square = squares.item(i);
403 if (square.id != getSquareId(move.start))
404 // HACK for animation:
405 // (with positive translate, image slides "under background")
406 square.style.zIndex = "-1";
408 movingPiece.style.transform =
409 "translate(" + translation.x + "px," + translation.y + "px)";
410 movingPiece.style.transitionDuration = "0.25s";
411 movingPiece.style.zIndex = "3000";
413 for (let i = 0; i < squares.length; i++)
414 squares.item(i).style.zIndex = "auto";
415 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
420 emitFenIfAnalyze: function() {
421 if (this.game.mode == "analyze") {
422 let fen = this.game.fenStart;
423 if (!!this.lastMove) {
424 if (Array.isArray(this.lastMove)) {
425 const L = this.lastMove.length;
426 fen = this.lastMove[L-1].fen;
428 else fen = this.lastMove.fen;
430 this.$emit("fenchange", fen);
433 clickSquare: function(square) {
434 // Some variants make use of a single click at specific times:
435 const move_s = this.vr.doClick(square);
437 if (!Array.isArray(move_s)) this.play(move_s);
438 else this.$refs["board"].choices = move_s;
441 // "light": if gotoMove() or gotoEnd()
442 play: function(move, received, light, autoplay) {
443 // Freeze while choices are shown:
445 !!this.$refs["board"].selectedPiece ||
446 this.$refs["board"].choices.length > 0
450 const navigate = !move;
451 // Forbid navigation during autoplay:
452 if (navigate && this.autoplay && !autoplay) return;
453 // Forbid playing outside analyze mode, except if move is received.
454 // Sufficient condition because Board already knows which turn it is.
456 this.mode != "analyze" &&
459 (this.game.score != "*" || this.cursor < this.moves.length - 1)
464 if (this.autoplay || this.inPlay) {
465 // Received moves while autoplaying are stacked,
466 // and in observed games they could arrive too fast:
467 this.stackToPlay.unshift(move);
470 if (this.mode == "analyze") this.toggleAnalyze();
471 if (this.cursor < this.moves.length - 1)
472 // To play a received move, cursor must be at the end of the game:
476 // The board may show some possible moves: (TODO: bad solution)
477 this.$refs["board"].resetCurrentAttempt();
478 const playSubmove = (smove) => {
479 smove.notation = this.vr.getNotation(smove);
480 smove.unambiguous = V.GetUnambiguousNotation(smove);
482 if (this.inMultimove && !!this.lastMove) {
483 if (!Array.isArray(this.lastMove))
484 this.lastMove = [this.lastMove, smove];
485 else this.lastMove.push(smove);
487 if (!this.inMultimove) {
489 this.lastMove = smove;
490 // Condition is "!navigate" but we mean "!this.autoplay"
492 if (this.cursor < this.moves.length - 1)
493 this.moves = this.moves.slice(0, this.cursor + 1);
494 this.moves.push(smove);
496 this.inMultimove = true; //potentially
498 } else if (!navigate) {
499 // Already in the middle of a multi-move
500 const L = this.moves.length;
501 if (!Array.isArray(this.moves[L-1]))
502 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
503 else this.moves[L-1].push(smove);
506 const playMove = () => {
508 ["all", "highlight"].includes(V.ShowMoves) &&
509 (this.autoplay || !!received)
511 if (!Array.isArray(move)) move = [move];
514 const initurn = this.vr.turn;
515 (function executeMove() {
516 const smove = move[moveIdx++];
517 // NOTE: condition "smove.start.x >= 0" required for Dynamo,
518 // because second move may be empty. noHighlight condition
519 // is used at least for Chakart.
520 if (animate && smove.start.x >= 0 && !smove.end.noHighlight) {
521 self.animateMove(smove, () => {
523 if (moveIdx < move.length) setTimeout(executeMove, 500);
524 else afterMove(smove, initurn);
528 if (moveIdx < move.length) executeMove();
529 else afterMove(smove, initurn);
533 const computeScore = () => {
534 const score = this.vr.getCurrentScore();
536 if (["1-0", "0-1"].includes(score)) {
537 if (Array.isArray(this.lastMove)) {
538 const L = this.lastMove.length;
539 this.lastMove[L - 1].notation += "#";
541 else this.lastMove.notation += "#";
544 if (score != "*" && ["analyze", "versus"].includes(this.mode)) {
545 const message = getScoreMessage(score);
546 // Show score on screen
547 this.showEndgameMsg(score + " . " + this.st.tr[message]);
551 const afterMove = (smove, initurn) => {
552 if (this.vr.turn != initurn) {
553 // Turn has changed: move is complete
555 // NOTE: only FEN of last sub-move is required (=> setting it here)
556 smove.fen = this.vr.getFen();
557 this.emitFenIfAnalyze();
558 this.inMultimove = false;
559 this.incheck = this.vr.getCheckSquares();
560 if (this.incheck.length > 0) smove.notation += "+";
561 this.score = computeScore();
563 if (this.cursor < this.moves.length - 1)
564 setTimeout(() => this.play(null, null, null, "autoplay"), 1000);
566 this.autoplay = false;
567 if (this.stackToPlay.length > 0)
568 // Move(s) arrived in-between
569 this.play(this.stackToPlay.pop(), "received");
572 if (this.mode != "analyze" && !navigate) {
574 // Post-processing (e.g. computer play).
575 const L = this.moves.length;
576 // NOTE: always emit the score, even in unfinished
577 this.$emit("newmove", this.moves[L-1], { score: this.score });
580 if (this.stackToPlay.length > 0)
581 // Move(s) arrived in-between
582 this.play(this.stackToPlay.pop(), "received");
587 // NOTE: navigate and received are mutually exclusive
589 // The move to navigate to is necessarily full:
590 if (this.cursor == this.moves.length - 1) return; //no more moves
591 move = this.moves[this.cursor + 1];
592 if (!this.autoplay) {
593 // Just play the move:
594 if (!Array.isArray(move)) move = [move];
595 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
597 this.lastMove = move;
598 this.incheck = this.vr.getCheckSquares();
599 this.score = computeScore();
600 this.emitFenIfAnalyze();
608 cancelCurrentMultimove: function() {
609 const L = this.moves.length;
610 let move = this.moves[L-1];
611 if (!Array.isArray(move)) move = [move];
612 for (let i = move.length - 1; i >= 0; i--) this.vr.undo(move[i]);
615 this.inMultimove = false;
617 cancelLastMove: function() {
618 // The last played move was canceled (corr game)
622 // "light": if gotoMove() or gotoBegin()
623 undo: function(move, light) {
626 !!this.$refs["board"].selectedPiece ||
627 this.$refs["board"].choices.length > 0
631 this.$refs["board"].resetCurrentAttempt();
632 if (this.inMultimove) {
633 this.cancelCurrentMultimove();
634 this.incheck = this.vr.getCheckSquares();
635 if (this.cursor >= 0) this.lastMove = this.moves[this.cursor];
636 else this.lastMove = null;
640 this.moves.length > 0 && this.moves[0].notation == "..."
643 if (this.cursor < minCursor) return; //no more moves
644 move = this.moves[this.cursor];
646 this.$refs["board"].resetCurrentAttempt();
647 undoMove(move, this.vr);
648 if (light) this.cursor--;
650 this.positionCursorTo(this.cursor - 1);
651 this.incheck = this.vr.getCheckSquares();
652 this.emitFenIfAnalyze();
656 gotoMove: function(index) {
659 !!this.$refs["board"].selectedPiece ||
660 this.$refs["board"].choices.length > 0
664 this.$refs["board"].resetCurrentAttempt();
665 if (this.inMultimove) this.cancelCurrentMultimove();
666 if (index == this.cursor) return;
667 if (index < this.cursor) {
668 while (this.cursor > index)
669 this.undo(null, null, "light");
672 // index > this.cursor)
673 while (this.cursor < index)
674 this.play(null, null, "light");
676 // NOTE: next line also re-assign cursor, but it's very light
677 this.positionCursorTo(index);
678 this.incheck = this.vr.getCheckSquares();
679 this.emitFenIfAnalyze();
681 gotoBegin: function() {
684 !!this.$refs["board"].selectedPiece ||
685 this.$refs["board"].choices.length > 0
689 this.$refs["board"].resetCurrentAttempt();
690 if (this.inMultimove) this.cancelCurrentMultimove();
692 this.moves.length > 0 && this.moves[0].notation == "..."
695 while (this.cursor >= minCursor) this.undo(null, null, "light");
696 this.lastMove = (minCursor == 1 ? this.moves[0] : null);
697 this.incheck = this.vr.getCheckSquares();
698 this.emitFenIfAnalyze();
700 gotoEnd: function() {
701 if (this.cursor == this.moves.length - 1) return;
702 this.gotoMove(this.moves.length - 1);
705 if (this.$refs["board"].choices.length > 0) return;
706 this.orientation = V.GetOppCol(this.orientation);
712 <style lang="sass" scoped>
713 [type="checkbox"]#modalEog+div .card
727 display: inline-block
741 background-color: #FACF8C
746 @media screen and (max-width: 767px)
755 // TODO: later, maybe, allow movesList of variable width
756 // or e.g. between 250 and 350px (but more complicated)
762 @media screen and (max-width: 767px)