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 @reset-arrows="resetArrows"
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() {
124 return this.game.score != "*"
126 : (!!this.vr ? this.vr.showMoves : "none");
128 showTurn: function() {
130 this.game.score == '*' &&
133 this.vr.showMoves != "all" ||
135 this.vr.showFirstTurn
139 canAnalyze: function() {
141 this.game.mode != "analyze" &&
142 !!this.vr && this.vr.canAnalyze
145 canFlip: function() {
146 return !!this.vr && this.vr.canFlip;
148 allowDownloadPGN: function() {
150 this.game.score != "*" ||
151 (!!this.vr && this.vr.showMoves == "all")
155 created: function() {
156 if (!!this.game.fenStart) this.re_setVariables();
158 mounted: function() {
159 if (!("ontouchstart" in window)) {
161 const baseGameDiv = document.getElementById("baseGame");
162 baseGameDiv.tabIndex = 0;
163 baseGameDiv.addEventListener("click", this.focusBg);
164 baseGameDiv.addEventListener("keydown", this.handleKeys);
165 baseGameDiv.addEventListener("wheel", this.handleScroll);
167 document.getElementById("eogDiv")
168 .addEventListener("click", processModalClick);
170 beforeDestroy: function() {
171 // TODO: probably not required
172 this.autoplay = false;
175 focusBg: function() {
176 document.getElementById("baseGame").focus();
178 handleKeys: function(e) {
179 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
198 handleScroll: function(e) {
200 if (e.deltaY < 0) this.undo();
201 else if (e.deltaY > 0) this.play();
203 resetArrows: function() {
204 // TODO: make arrows scale with board, and remove this
205 this.$refs["board"].cancelResetArrows();
207 showRules: function() {
208 // The button is here only on Game page:
209 document.getElementById("modalRules").checked = true;
211 re_setVariables: function(game) {
212 if (!game) game = this.game; //in case of...
213 this.endgameMessage = "";
214 // "w": default orientation for observed games
215 this.orientation = game.mycolor || "w";
216 this.mode = game.mode || game.type; //TODO: merge...
217 this.moves = JSON.parse(JSON.stringify(game.moves || []));
218 // Post-processing: decorate each move with notation and FEN
219 this.vr = new V(game.fenStart);
220 this.inMultimove = false; //in case of
221 this.$refs["board"].resetCurrentAttempt(); //also in case of
222 let analyseBtn = document.getElementById("analyzeBtn");
223 if (!!analyseBtn) analyseBtn.classList.remove("active");
224 const parsedFen = V.ParseFen(game.fenStart);
225 const firstMoveColor = parsedFen.turn;
226 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2) + 1;
227 let L = this.moves.length;
232 this.moves.forEach((move,idx) => {
233 // Strategy working also for multi-moves:
234 if (!Array.isArray(move)) move = [move];
235 const Lm = move.length;
236 move.forEach((m,idxM) => {
237 m.notation = this.vr.getNotation(m);
238 m.unambiguous = V.GetUnambiguousNotation(m);
240 const checkSquares = this.vr.getCheckSquares();
241 if (checkSquares.length > 0) m.notation += "+";
242 if (idxM == Lm - 1) m.fen = this.vr.getFen();
243 if (idx == L - 1 && idxM == Lm - 1) {
244 this.incheck = checkSquares;
245 this.score = this.vr.getCurrentScore();
246 if (["1-0", "0-1"].includes(this.score)) m.notation += "#";
250 if (firstMoveColor == "b") {
251 // 'start' & 'end' is required for Board component
255 start: { x: -1, y: -1 },
256 end: { x: -1, y: -1 },
261 this.positionCursorTo(L - 1);
263 positionCursorTo: function(index) {
265 // Note: last move in moves array might be a multi-move
266 if (index >= 0) this.lastMove = this.moves[index];
267 else this.lastMove = null;
269 toggleAnalyze: function() {
270 // Freeze while choices are shown (and autoplay has priority)
271 if (this.$refs["board"].choices.length > 0 || this.autoplay) return;
272 if (this.mode != "analyze") {
273 // Enter analyze mode:
274 if (this.inMultimove) this.cancelCurrentMultimove();
275 this.gameMode = this.mode; //was not 'analyze'
276 this.mode = "analyze";
277 this.gameCursor = this.cursor;
278 this.gameMoves = JSON.parse(JSON.stringify(this.moves));
279 document.getElementById("analyzeBtn").classList.add("active");
282 // Exit analyze mode:
283 this.mode = this.gameMode ;
284 this.cursor = this.gameCursor;
285 this.moves = this.gameMoves;
286 let fen = this.game.fenStart;
287 if (this.cursor >= 0) {
288 let mv = this.moves[this.cursor];
289 if (!Array.isArray(mv)) mv = [mv];
290 fen = mv[mv.length-1].fen;
292 this.vr = new V(fen);
293 this.inMultimove = false; //in case of
294 this.$refs["board"].resetCurrentAttempt(); //also in case of
295 this.incheck = this.vr.getCheckSquares();
296 if (this.cursor >= 0) this.lastMove = this.moves[this.cursor];
297 else this.lastMove = null;
298 document.getElementById("analyzeBtn").classList.remove("active");
301 download: function() {
302 const content = this.getPgn();
303 // Prepare and trigger download link
304 let downloadAnchor = document.getElementById("download");
305 downloadAnchor.setAttribute("download", "game.pgn");
306 downloadAnchor.href =
307 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
308 downloadAnchor.click();
312 pgn += '[Site "vchess.club"]\n';
313 pgn += '[Variant "' + this.game.vname + '"]\n';
314 const gdt = getDate(new Date(this.game.created || Date.now()));
315 pgn += '[Date "' + gdt + '"]\n';
316 pgn += '[White "' + this.game.players[0].name + '"]\n';
317 pgn += '[Black "' + this.game.players[1].name + '"]\n';
318 pgn += '[Fen "' + this.game.fenStart + '"]\n';
319 pgn += '[Result "' + this.game.score + '"]\n';
321 pgn += '[Url "' + params.serverUrl + '/game/' + this.game.id + '"]\n';
322 if (!!this.game.cadence)
323 pgn += '[Cadence "' + this.game.cadence + '"]\n';
325 for (let i = 0; i < this.moves.length; i += 2) {
326 if (i > 0) pgn += " ";
327 // Adjust dots notation for a better display:
328 let fullNotation = getFullNotation(this.moves[i]);
329 if (fullNotation == "...") fullNotation = "..";
330 pgn += (i / 2 + this.firstMoveNumber) + "." + fullNotation;
331 if (i+1 < this.moves.length)
332 pgn += " " + getFullNotation(this.moves[i+1]);
335 for (let i = 0; i < this.moves.length; i += 2) {
336 const moveNumber = i / 2 + this.firstMoveNumber;
337 // Skip "dots move", useless for machine reading:
338 if (this.moves[i].notation != "...") {
339 pgn += moveNumber + ".w " +
340 getFullNotation(this.moves[i], "unambiguous") + "\n";
342 if (i+1 < this.moves.length) {
343 pgn += moveNumber + ".b " +
344 getFullNotation(this.moves[i+1], "unambiguous") + "\n";
349 showEndgameMsg: function(message) {
350 this.endgameMessage = message;
351 document.getElementById("modalEog").checked = true;
353 runAutoplay: function() {
355 this.autoplay = false;
356 if (this.stackToPlay.length > 0)
357 // Move(s) arrived in-between
358 this.play(this.stackToPlay.pop(), "received");
360 else if (this.cursor < this.moves.length - 1) {
361 this.autoplay = true;
362 this.play(null, null, null, "autoplay");
365 // Animate an elementary move
366 animateMove: function(move, callback) {
367 let startSquare = document.getElementById(getSquareId(move.start));
368 if (!startSquare) return; //shouldn't happen but...
369 let endSquare = document.getElementById(getSquareId(move.end));
370 let rectStart = startSquare.getBoundingClientRect();
371 let rectEnd = endSquare.getBoundingClientRect();
373 x: rectEnd.x - rectStart.x,
374 y: rectEnd.y - rectStart.y
376 let movingPiece = document.querySelector(
377 "#" + getSquareId(move.start) + " > img.piece"
379 // For some unknown reasons Opera get "movingPiece == null" error
380 // TODO: is it calling 'animate()' twice ? One extra time ?
381 if (!movingPiece) return;
382 const squares = document.getElementsByClassName("board");
383 for (let i = 0; i < squares.length; i++) {
384 let square = squares.item(i);
385 if (square.id != getSquareId(move.start))
386 // HACK for animation:
387 // (with positive translate, image slides "under background")
388 square.style.zIndex = "-1";
390 movingPiece.style.transform =
391 "translate(" + translation.x + "px," + translation.y + "px)";
392 movingPiece.style.transitionDuration = "0.25s";
393 movingPiece.style.zIndex = "3000";
395 for (let i = 0; i < squares.length; i++)
396 squares.item(i).style.zIndex = "auto";
397 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
402 emitFenIfAnalyze: function() {
403 if (this.game.mode == "analyze") {
404 let fen = this.game.fenStart;
405 if (!!this.lastMove) {
406 if (Array.isArray(this.lastMove)) {
407 const L = this.lastMove.length;
408 fen = this.lastMove[L-1].fen;
410 else fen = this.lastMove.fen;
412 this.$emit("fenchange", fen);
415 clickSquare: function(square) {
416 // Some variants make use of a single click at specific times:
417 const move = this.vr.doClick(square);
418 if (!!move) this.play(move);
420 // "light": if gotoMove() or gotoEnd()
421 play: function(move, received, light, autoplay) {
422 // Freeze while choices are shown:
423 if (this.$refs["board"].choices.length > 0) return;
424 const navigate = !move;
425 // Forbid navigation during autoplay:
426 if (navigate && this.autoplay && !autoplay) return;
427 // Forbid playing outside analyze mode, except if move is received.
428 // Sufficient condition because Board already knows which turn it is.
430 this.mode != "analyze" &&
433 (this.game.score != "*" || this.cursor < this.moves.length - 1)
438 if (this.autoplay || this.inPlay) {
439 // Received moves while autoplaying are stacked,
440 // and in observed games they could arrive too fast:
441 this.stackToPlay.unshift(move);
445 if (this.mode == "analyze") this.toggleAnalyze();
446 if (this.cursor < this.moves.length - 1)
447 // To play a received move, cursor must be at the end of the game:
450 // The board may show some the possible moves: (TODO: bad solution)
451 this.$refs["board"].resetCurrentAttempt();
452 const playSubmove = (smove) => {
453 smove.notation = this.vr.getNotation(smove);
454 smove.unambiguous = V.GetUnambiguousNotation(smove);
456 if (this.inMultimove && !!this.lastMove) {
457 if (!Array.isArray(this.lastMove))
458 this.lastMove = [this.lastMove, smove];
459 else this.lastMove.push(smove);
461 // Is opponent (or me) in check?
462 this.incheck = this.vr.getCheckSquares();
463 if (this.incheck.length > 0) smove.notation += "+";
464 if (!this.inMultimove) {
466 this.lastMove = smove;
467 // Condition is "!navigate" but we mean "!this.autoplay"
469 if (this.cursor < this.moves.length - 1)
470 this.moves = this.moves.slice(0, this.cursor + 1);
471 this.moves.push(smove);
473 this.inMultimove = true; //potentially
475 } else if (!navigate) {
476 // Already in the middle of a multi-move
477 const L = this.moves.length;
478 if (!Array.isArray(this.moves[L-1]))
479 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
480 else this.moves[L-1].push(smove);
483 const playMove = () => {
485 ["all", "highlight"].includes(V.ShowMoves) &&
486 (this.autoplay || !!received)
488 if (!Array.isArray(move)) move = [move];
491 const initurn = this.vr.turn;
492 (function executeMove() {
493 const smove = move[moveIdx++];
494 // NOTE: condition "smove.start.x >= 0" required for Dynamo,
495 // because second move may be empty.
496 if (animate && smove.start.x >= 0) {
497 self.animateMove(smove, () => {
499 if (moveIdx < move.length) setTimeout(executeMove, 500);
500 else afterMove(smove, initurn);
504 if (moveIdx < move.length) executeMove();
505 else afterMove(smove, initurn);
509 const computeScore = () => {
510 const score = this.vr.getCurrentScore();
512 if (["1-0", "0-1"].includes(score)) {
513 if (Array.isArray(this.lastMove)) {
514 const L = this.lastMove.length;
515 this.lastMove[L - 1].notation += "#";
517 else this.lastMove.notation += "#";
520 if (score != "*" && ["analyze", "versus"].includes(this.mode)) {
521 const message = getScoreMessage(score);
522 // Show score on screen
523 this.showEndgameMsg(score + " . " + this.st.tr[message]);
527 const afterMove = (smove, initurn) => {
528 if (this.vr.turn != initurn) {
529 // Turn has changed: move is complete
531 // NOTE: only FEN of last sub-move is required (=> setting it here)
532 smove.fen = this.vr.getFen();
533 this.emitFenIfAnalyze();
534 this.inMultimove = false;
535 this.score = computeScore();
537 if (this.cursor < this.moves.length - 1)
538 setTimeout(() => this.play(null, null, null, "autoplay"), 1000);
540 this.autoplay = false;
541 if (this.stackToPlay.length > 0)
542 // Move(s) arrived in-between
543 this.play(this.stackToPlay.pop(), "received");
546 if (this.mode != "analyze" && !navigate) {
548 // Post-processing (e.g. computer play).
549 const L = this.moves.length;
550 // NOTE: always emit the score, even in unfinished
551 this.$emit("newmove", this.moves[L-1], { score: this.score });
554 if (this.stackToPlay.length > 0)
555 // Move(s) arrived in-between
556 this.play(this.stackToPlay.pop(), "received");
561 // NOTE: navigate and received are mutually exclusive
563 // The move to navigate to is necessarily full:
564 if (this.cursor == this.moves.length - 1) return; //no more moves
565 move = this.moves[this.cursor + 1];
566 if (!this.autoplay) {
567 // Just play the move:
568 if (!Array.isArray(move)) move = [move];
569 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
571 this.lastMove = move;
572 this.incheck = this.vr.getCheckSquares();
573 this.score = computeScore();
574 this.emitFenIfAnalyze();
582 cancelCurrentMultimove: function() {
583 const L = this.moves.length;
584 let move = this.moves[L-1];
585 if (!Array.isArray(move)) move = [move];
586 for (let i = move.length - 1; i >= 0; i--) this.vr.undo(move[i]);
589 this.inMultimove = false;
591 cancelLastMove: function() {
592 // The last played move was canceled (corr game)
596 // "light": if gotoMove() or gotoBegin()
597 undo: function(move, light) {
598 // Freeze while choices are shown:
599 if (this.$refs["board"].choices.length > 0 || this.autoplay) return;
600 this.$refs["board"].resetCurrentAttempt();
601 if (this.inMultimove) {
602 this.cancelCurrentMultimove();
603 this.incheck = this.vr.getCheckSquares();
604 if (this.cursor >= 0) this.lastMove = this.moves[this.cursor];
605 else this.lastMove = null;
609 this.moves.length > 0 && this.moves[0].notation == "..."
612 if (this.cursor < minCursor) return; //no more moves
613 move = this.moves[this.cursor];
615 this.$refs["board"].resetCurrentAttempt();
616 undoMove(move, this.vr);
617 if (light) this.cursor--;
619 this.positionCursorTo(this.cursor - 1);
620 this.incheck = this.vr.getCheckSquares();
621 this.emitFenIfAnalyze();
625 gotoMove: function(index) {
626 if (this.$refs["board"].choices.length > 0 || this.autoplay) return;
627 this.$refs["board"].resetCurrentAttempt();
628 if (this.inMultimove) this.cancelCurrentMultimove();
629 if (index == this.cursor) return;
630 if (index < this.cursor) {
631 while (this.cursor > index)
632 this.undo(null, null, "light");
635 // index > this.cursor)
636 while (this.cursor < index)
637 this.play(null, null, "light");
639 // NOTE: next line also re-assign cursor, but it's very light
640 this.positionCursorTo(index);
641 this.incheck = this.vr.getCheckSquares();
642 this.emitFenIfAnalyze();
644 gotoBegin: function() {
645 if (this.$refs["board"].choices.length > 0 || this.autoplay) return;
646 this.$refs["board"].resetCurrentAttempt();
647 if (this.inMultimove) this.cancelCurrentMultimove();
649 this.moves.length > 0 && this.moves[0].notation == "..."
652 while (this.cursor >= minCursor) this.undo(null, null, "light");
653 this.lastMove = (minCursor == 1 ? this.moves[0] : null);
654 this.incheck = this.vr.getCheckSquares();
655 this.emitFenIfAnalyze();
657 gotoEnd: function() {
658 if (this.$refs["board"].choices.length > 0 || this.autoplay) return;
659 this.$refs["board"].resetCurrentAttempt();
660 if (this.cursor == this.moves.length - 1) return;
661 this.gotoMove(this.moves.length - 1);
662 this.emitFenIfAnalyze();
665 if (this.$refs["board"].choices.length > 0) return;
666 this.orientation = V.GetOppCol(this.orientation);
672 <style lang="sass" scoped>
673 [type="checkbox"]#modalEog+div .card
687 display: inline-block
701 background-color: #FACF8C
706 @media screen and (max-width: 767px)
715 // TODO: later, maybe, allow movesList of variable width
716 // or e.g. between 250 and 350px (but more complicated)
722 @media screen and (max-width: 767px)