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(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
104 if (!this.vr) return "";
105 if (this.vr.showMoves != "all") {
107 (this.vr.turn == 'w' ? "White" : "Black") + " to move"];
109 // Cannot flip: racing king or circular chess
111 this.vr.movesCount == 0 && this.game.mycolor == "w"
112 ? this.st.tr["It's your turn!"]
116 showFen: function() {
118 this.mode == "analyze" &&
119 this.$router.currentRoute.path.indexOf("/analyse") === -1
122 // TODO: is it OK to pass "computed" as properties?
123 // Also, some are seemingly not recomputed when vr is initialized.
124 showMoves: function() {
125 return this.game.score != "*"
127 : (!!this.vr ? this.vr.showMoves : "none");
129 showTurn: function() {
131 this.game.score == '*' &&
132 !!this.vr && (this.vr.showMoves != "all" || !this.vr.canFlip)
135 canAnalyze: function() {
137 this.game.mode != "analyze" &&
138 !!this.vr && this.vr.canAnalyze
141 canFlip: function() {
142 return !!this.vr && this.vr.canFlip;
144 allowDownloadPGN: function() {
146 this.game.score != "*" ||
147 (!!this.vr && this.vr.showMoves == "all")
151 created: function() {
152 if (!!this.game.fenStart) this.re_setVariables();
154 mounted: function() {
155 if (!("ontouchstart" in window)) {
157 const baseGameDiv = document.getElementById("baseGame");
158 baseGameDiv.tabIndex = 0;
159 baseGameDiv.addEventListener("click", this.focusBg);
160 baseGameDiv.addEventListener("keydown", this.handleKeys);
161 baseGameDiv.addEventListener("wheel", this.handleScroll);
163 document.getElementById("eogDiv")
164 .addEventListener("click", processModalClick);
166 beforeDestroy: function() {
167 if (!!this.autoplayLoop) clearInterval(this.autoplayLoop);
170 focusBg: function() {
171 document.getElementById("baseGame").focus();
173 handleKeys: function(e) {
174 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
193 handleScroll: function(e) {
195 if (e.deltaY < 0) this.undo();
196 else if (e.deltaY > 0) this.play();
198 resetArrows: function() {
199 // TODO: make arrows scale with board, and remove this
200 this.$refs["board"].cancelResetArrows();
202 showRules: function() {
203 // The button is here only on Game page:
204 document.getElementById("modalRules").checked = true;
206 re_setVariables: function(game) {
207 if (!game) game = this.game; //in case of...
208 this.endgameMessage = "";
209 // "w": default orientation for observed games
210 this.orientation = game.mycolor || "w";
211 this.mode = game.mode || game.type; //TODO: merge...
212 this.moves = JSON.parse(JSON.stringify(game.moves || []));
213 // Post-processing: decorate each move with notation and FEN
214 this.vr = new V(game.fenStart);
215 const parsedFen = V.ParseFen(game.fenStart);
216 const firstMoveColor = parsedFen.turn;
217 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2) + 1;
218 let L = this.moves.length;
219 this.moves.forEach((move,idx) => {
220 // Strategy working also for multi-moves:
221 if (!Array.isArray(move)) move = [move];
222 const Lm = move.length;
223 move.forEach((m,idxM) => {
224 m.notation = this.vr.getNotation(m);
225 m.unambiguous = V.GetUnambiguousNotation(m);
227 const checkSquares = this.vr.getCheckSquares();
228 if (checkSquares.length > 0) m.notation += "+";
229 if (idxM == Lm - 1) m.fen = this.vr.getFen();
230 if (idx == L - 1 && idxM == Lm - 1) {
231 this.incheck = checkSquares;
232 const score = this.vr.getCurrentScore();
233 if (["1-0", "0-1"].includes(score)) m.notation += "#";
237 if (firstMoveColor == "b") {
238 // 'start' & 'end' is required for Board component
242 start: { x: -1, y: -1 },
243 end: { x: -1, y: -1 },
248 this.positionCursorTo(L - 1);
250 positionCursorTo: function(index) {
252 // Note: last move in moves array might be a multi-move
253 if (index >= 0) this.lastMove = this.moves[index];
254 else this.lastMove = null;
256 toggleAnalyze: function() {
257 if (this.mode != "analyze") {
258 // Enter analyze mode:
259 this.gameMode = this.mode; //was not 'analyze'
260 this.mode = "analyze";
261 this.gameCursor = this.cursor;
262 this.gameMoves = JSON.parse(JSON.stringify(this.moves));
263 document.getElementById("analyzeBtn").classList.add("active");
266 // Exit analyze mode:
267 this.mode = this.gameMode ;
268 this.cursor = this.gameCursor;
269 this.moves = this.gameMoves;
270 let fen = this.game.fenStart;
271 if (this.cursor >= 0) {
272 let mv = this.moves[this.cursor];
273 if (!Array.isArray(mv)) mv = [mv];
274 fen = mv[mv.length-1].fen;
276 this.vr = new V(fen);
277 document.getElementById("analyzeBtn").classList.remove("active");
280 download: function() {
281 const content = this.getPgn();
282 // Prepare and trigger download link
283 let downloadAnchor = document.getElementById("download");
284 downloadAnchor.setAttribute("download", "game.pgn");
285 downloadAnchor.href =
286 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
287 downloadAnchor.click();
291 pgn += '[Site "vchess.club"]\n';
292 pgn += '[Variant "' + this.game.vname + '"]\n';
293 const gdt = getDate(new Date(this.game.created || Date.now()));
294 pgn += '[Date "' + gdt + '"]\n';
295 pgn += '[White "' + this.game.players[0].name + '"]\n';
296 pgn += '[Black "' + this.game.players[1].name + '"]\n';
297 pgn += '[Fen "' + this.game.fenStart + '"]\n';
298 pgn += '[Result "' + this.game.score + '"]\n';
300 pgn += '[Url "' + params.serverUrl + '/game/' + this.game.id + '"]\n';
301 if (!!this.game.cadence)
302 pgn += '[Cadence "' + this.game.cadence + '"]\n';
304 for (let i = 0; i < this.moves.length; i += 2) {
305 if (i > 0) pgn += " ";
306 // Adjust dots notation for a better display:
307 let fullNotation = getFullNotation(this.moves[i]);
308 if (fullNotation == "...") fullNotation = "..";
309 pgn += (i / 2 + this.firstMoveNumber) + "." + fullNotation;
310 if (i+1 < this.moves.length)
311 pgn += " " + getFullNotation(this.moves[i+1]);
314 for (let i = 0; i < this.moves.length; i += 2) {
315 const moveNumber = i / 2 + this.firstMoveNumber;
316 // Skip "dots move", useless for machine reading:
317 if (this.moves[i].notation != "...") {
318 pgn += moveNumber + ".w " +
319 getFullNotation(this.moves[i], "unambiguous") + "\n";
321 if (i+1 < this.moves.length) {
322 pgn += moveNumber + ".b " +
323 getFullNotation(this.moves[i+1], "unambiguous") + "\n";
328 showEndgameMsg: function(message) {
329 this.endgameMessage = message;
330 document.getElementById("modalEog").checked = true;
332 runAutoplay: function() {
333 const infinitePlay = () => {
334 if (this.cursor == this.moves.length - 1) {
335 clearInterval(this.autoplayLoop);
336 this.autoplayLoop = null;
337 this.autoplay = false;
340 if (this.inPlay || this.inMultimove)
346 this.autoplay = false;
347 clearInterval(this.autoplayLoop);
348 this.autoplayLoop = null;
350 this.autoplay = true;
354 this.autoplayLoop = setInterval(infinitePlay, 1500);
356 // Small delay otherwise the first move is played too fast
361 // Animate an elementary move
362 animateMove: function(move, callback) {
363 let startSquare = document.getElementById(getSquareId(move.start));
364 if (!startSquare) return; //shouldn't happen but...
365 let endSquare = document.getElementById(getSquareId(move.end));
366 let rectStart = startSquare.getBoundingClientRect();
367 let rectEnd = endSquare.getBoundingClientRect();
369 x: rectEnd.x - rectStart.x,
370 y: rectEnd.y - rectStart.y
372 let movingPiece = document.querySelector(
373 "#" + getSquareId(move.start) + " > img.piece"
375 // For some unknown reasons Opera get "movingPiece == null" error
376 // TODO: is it calling 'animate()' twice ? One extra time ?
377 if (!movingPiece) return;
378 const squares = document.getElementsByClassName("board");
379 for (let i = 0; i < squares.length; i++) {
380 let square = squares.item(i);
381 if (square.id != getSquareId(move.start))
382 // HACK for animation:
383 // (with positive translate, image slides "under background")
384 square.style.zIndex = "-1";
386 movingPiece.style.transform =
387 "translate(" + translation.x + "px," + translation.y + "px)";
388 movingPiece.style.transitionDuration = "0.25s";
389 movingPiece.style.zIndex = "3000";
391 for (let i = 0; i < squares.length; i++)
392 squares.item(i).style.zIndex = "auto";
393 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
398 emitFenIfAnalyze: function() {
399 if (this.game.mode == "analyze") {
400 let fen = this.game.fenStart;
401 if (!!this.lastMove) {
402 if (Array.isArray(this.lastMove)) {
403 const L = this.lastMove.length;
404 fen = this.lastMove[L-1].fen;
406 else fen = this.lastMove.fen;
408 this.$emit("fenchange", fen);
411 clickSquare: function(square) {
412 // Some variants make use of a single click at specific times:
413 const move = this.vr.doClick(square);
414 if (!!move) this.play(move);
416 // "light": if gotoMove() or gotoEnd()
417 play: function(move, received, light, noemit) {
418 // Freeze while choices are shown:
419 if (this.$refs["board"].choices.length > 0) return;
420 // The board may show some the possible moves: (TODO: bad solution)
421 this.$refs["board"].resetCurrentAttempt();
424 // Received moves in observed games can arrive too fast:
425 this.stackToPlay.unshift(move);
430 const navigate = !move;
431 const playSubmove = (smove) => {
432 smove.notation = this.vr.getNotation(smove);
433 smove.unambiguous = V.GetUnambiguousNotation(smove);
435 if (this.inMultimove && !!this.lastMove) {
436 if (!Array.isArray(this.lastMove))
437 this.lastMove = [this.lastMove, smove];
438 else this.lastMove.push(smove);
440 // Is opponent (or me) in check?
441 this.incheck = this.vr.getCheckSquares();
442 if (this.incheck.length > 0) smove.notation += "+";
443 if (!this.inMultimove) {
445 this.lastMove = smove;
446 // Condition is "!navigate" but we mean "!this.autoplay"
448 if (this.cursor < this.moves.length - 1)
449 this.moves = this.moves.slice(0, this.cursor + 1);
450 this.moves.push(smove);
452 this.inMultimove = true; //potentially
454 } else if (!navigate) {
455 // Already in the middle of a multi-move
456 const L = this.moves.length;
457 if (!Array.isArray(this.moves[L-1]))
458 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
459 else this.moves[L-1].push(smove);
462 const playMove = () => {
464 ["all", "highlight"].includes(V.ShowMoves) &&
465 (this.autoplay || !!received)
467 if (!Array.isArray(move)) move = [move];
470 const initurn = this.vr.turn;
471 (function executeMove() {
472 const smove = move[moveIdx++];
473 // NOTE: condition "smove.start.x >= 0" required for Dynamo,
474 // because second move may be empty.
475 if (animate && smove.start.x >= 0) {
476 self.animateMove(smove, () => {
478 if (moveIdx < move.length)
479 setTimeout(executeMove, 500);
480 else afterMove(smove, initurn);
484 if (moveIdx < move.length) executeMove();
485 else afterMove(smove, initurn);
489 const computeScore = () => {
490 const score = this.vr.getCurrentScore();
492 if (["1-0","0-1"].includes(score)) {
493 if (Array.isArray(this.lastMove)) {
494 const L = this.lastMove.length;
495 this.lastMove[L - 1].notation += "#";
497 else this.lastMove.notation += "#";
500 if (score != "*" && this.mode == "analyze") {
501 const message = getScoreMessage(score);
502 // Just show score on screen (allow undo)
503 this.showEndgameMsg(score + " . " + this.st.tr[message]);
507 const afterMove = (smove, initurn) => {
508 if (this.vr.turn != initurn) {
509 // Turn has changed: move is complete
511 // NOTE: only FEN of last sub-move is required (=> setting it here)
512 smove.fen = this.vr.getFen();
513 this.emitFenIfAnalyze();
514 this.inMultimove = false;
515 this.score = computeScore();
516 if (this.mode != "analyze" && !navigate) {
518 // Post-processing (e.g. computer play).
519 const L = this.moves.length;
520 // NOTE: always emit the score, even in unfinished,
521 // to tell Game::processMove() that it's not a received move.
522 this.$emit("newmove", this.moves[L-1], { score: this.score });
525 if (this.stackToPlay.length > 0)
526 // Move(s) arrived in-between
527 this.play(this.stackToPlay.pop(), received, light, noemit);
532 // NOTE: navigate and received are mutually exclusive
534 // The move to navigate to is necessarily full:
535 if (this.cursor == this.moves.length - 1) return; //no more moves
536 move = this.moves[this.cursor + 1];
537 if (!this.autoplay) {
538 // Just play the move:
539 if (!Array.isArray(move)) move = [move];
540 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
542 this.lastMove = move;
543 this.incheck = this.vr.getCheckSquares();
544 this.score = computeScore();
545 this.emitFenIfAnalyze();
551 // Forbid playing outside analyze mode, except if move is received.
552 // Sufficient condition because Board already knows which turn it is.
554 this.mode != "analyze" &&
557 (this.game.score != "*" || this.cursor < this.moves.length - 1)
562 if (this.mode == "analyze") this.toggleAnalyze();
563 if (this.cursor < this.moves.length - 1)
564 // To play a received move, cursor must be at the end of the game:
569 cancelCurrentMultimove: function() {
570 const L = this.moves.length;
571 let move = this.moves[L-1];
572 if (!Array.isArray(move)) move = [move];
573 for (let i = move.length - 1; i >= 0; i--) this.vr.undo(move[i]);
576 this.inMultimove = false;
578 cancelLastMove: function() {
579 // The last played move was canceled (corr game)
583 // "light": if gotoMove() or gotoBegin()
584 undo: function(move, light) {
585 // Freeze while choices are shown:
586 if (this.$refs["board"].choices.length > 0) return;
587 this.$refs["board"].resetCurrentAttempt();
588 if (this.inMultimove) {
589 this.cancelCurrentMultimove();
590 this.incheck = this.vr.getCheckSquares();
594 this.moves.length > 0 && this.moves[0].notation == "..."
597 if (this.cursor < minCursor) return; //no more moves
598 move = this.moves[this.cursor];
600 this.$refs["board"].resetCurrentAttempt();
601 undoMove(move, this.vr);
602 if (light) this.cursor--;
604 this.positionCursorTo(this.cursor - 1);
605 this.incheck = this.vr.getCheckSquares();
606 this.emitFenIfAnalyze();
610 gotoMove: function(index) {
611 if (this.$refs["board"].choices.length > 0) return;
612 this.$refs["board"].resetCurrentAttempt();
613 if (this.inMultimove) this.cancelCurrentMultimove();
614 if (index == this.cursor) return;
615 if (index < this.cursor) {
616 while (this.cursor > index)
617 this.undo(null, null, "light");
620 // index > this.cursor)
621 while (this.cursor < index)
622 this.play(null, null, "light");
624 // NOTE: next line also re-assign cursor, but it's very light
625 this.positionCursorTo(index);
626 this.incheck = this.vr.getCheckSquares();
627 this.emitFenIfAnalyze();
629 gotoBegin: function() {
630 if (this.$refs["board"].choices.length > 0) return;
631 this.$refs["board"].resetCurrentAttempt();
632 if (this.inMultimove) this.cancelCurrentMultimove();
634 this.moves.length > 0 && this.moves[0].notation == "..."
637 while (this.cursor >= minCursor) this.undo(null, null, "light");
638 this.lastMove = (minCursor == 1 ? this.moves[0] : null);
639 this.incheck = this.vr.getCheckSquares();
640 this.emitFenIfAnalyze();
642 gotoEnd: function() {
643 if (this.$refs["board"].choices.length > 0) return;
644 this.$refs["board"].resetCurrentAttempt();
645 if (this.cursor == this.moves.length - 1) return;
646 this.gotoMove(this.moves.length - 1);
647 this.emitFenIfAnalyze();
650 if (this.$refs["board"].choices.length > 0) return;
651 this.orientation = V.GetOppCol(this.orientation);
657 <style lang="sass" scoped>
658 [type="checkbox"]#modalEog+div .card
671 display: inline-block
682 background-color: #FACF8C
687 @media screen and (max-width: 767px)
696 // TODO: later, maybe, allow movesList of variable width
697 // or e.g. between 250 and 350px (but more complicated)
703 @media screen and (max-width: 767px)