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"
65 // https://vchess.club/#/game/46
66 // Bug 35eme coup blanc Rx(P)e2, d2 et aussi 18eme coup blanc Rd7, Pxe6
67 // --> peut-être lié à prise, ou lié à getFen(), ou inMultimove pas changé car concatène à coup précédent...
68 // TODO: also fix moves played on smartphone, annoying shift...
70 import Board from "@/components/Board.vue";
71 import MoveList from "@/components/MoveList.vue";
72 import params from "@/parameters";
73 import { store } from "@/store";
74 import { getSquareId } from "@/utils/squareId";
75 import { getDate } from "@/utils/datetime";
76 import { processModalClick } from "@/utils/modalClick";
77 import { getScoreMessage } from "@/utils/scoring";
78 import { getFullNotation } from "@/utils/notation";
79 import { undoMove } from "@/utils/playUndo";
90 // NOTE: all following variables must be reset at the beginning of a game
91 vr: null, //VariantRules object, game state
95 score: "*", //'*' means 'unfinished'
97 cursor: -1, //index of the move just played
99 firstMoveNumber: 0, //for printing
100 incheck: [], //for Board
109 if (!this.vr) return "";
110 if (this.vr.showMoves != "all") {
112 (this.vr.turn == 'w' ? "White" : "Black") + " to move"];
114 // Cannot flip: racing king or circular chess
116 this.vr.movesCount == 0 && this.game.mycolor == "w"
117 ? this.st.tr["It's your turn!"]
121 showFen: function() {
123 this.mode == "analyze" &&
124 this.$router.currentRoute.path.indexOf("/analyse") === -1
127 // TODO: is it OK to pass "computed" as properties?
128 // Also, some are seemingly not recomputed when vr is initialized.
129 showMoves: function() {
130 return this.game.score != "*"
132 : (!!this.vr ? this.vr.showMoves : "none");
134 showTurn: function() {
136 this.game.score == '*' &&
137 !!this.vr && (this.vr.showMoves != "all" || !this.vr.canFlip)
140 canAnalyze: function() {
142 this.game.mode != "analyze" &&
143 !!this.vr && this.vr.canAnalyze
146 canFlip: function() {
147 return !!this.vr && this.vr.canFlip;
149 allowDownloadPGN: function() {
151 this.game.score != "*" ||
152 (!!this.vr && this.vr.showMoves == "all")
156 created: function() {
157 if (!!this.game.fenStart) this.re_setVariables();
159 mounted: function() {
160 if (!("ontouchstart" in window)) {
162 const baseGameDiv = document.getElementById("baseGame");
163 baseGameDiv.tabIndex = 0;
164 baseGameDiv.addEventListener("click", this.focusBg);
165 baseGameDiv.addEventListener("keydown", this.handleKeys);
166 baseGameDiv.addEventListener("wheel", this.handleScroll);
168 document.getElementById("eogDiv")
169 .addEventListener("click", processModalClick);
171 beforeDestroy: function() {
172 // TODO: probably not required
173 this.autoplay = false;
176 focusBg: function() {
177 document.getElementById("baseGame").focus();
179 handleKeys: function(e) {
180 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
199 handleScroll: function(e) {
201 if (e.deltaY < 0) this.undo();
202 else if (e.deltaY > 0) this.play();
204 resetArrows: function() {
205 // TODO: make arrows scale with board, and remove this
206 this.$refs["board"].cancelResetArrows();
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 const parsedFen = V.ParseFen(game.fenStart);
222 const firstMoveColor = parsedFen.turn;
223 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2) + 1;
224 let L = this.moves.length;
229 this.moves.forEach((move,idx) => {
230 // Strategy working also for multi-moves:
231 if (!Array.isArray(move)) move = [move];
232 const Lm = move.length;
233 move.forEach((m,idxM) => {
234 m.notation = this.vr.getNotation(m);
235 m.unambiguous = V.GetUnambiguousNotation(m);
237 const checkSquares = this.vr.getCheckSquares();
238 if (checkSquares.length > 0) m.notation += "+";
239 if (idxM == Lm - 1) m.fen = this.vr.getFen();
240 if (idx == L - 1 && idxM == Lm - 1) {
241 this.incheck = checkSquares;
242 this.score = this.vr.getCurrentScore();
243 if (["1-0", "0-1"].includes(this.score)) m.notation += "#";
247 if (firstMoveColor == "b") {
248 // 'start' & 'end' is required for Board component
252 start: { x: -1, y: -1 },
253 end: { x: -1, y: -1 },
258 this.positionCursorTo(L - 1);
260 positionCursorTo: function(index) {
262 // Note: last move in moves array might be a multi-move
263 if (index >= 0) this.lastMove = this.moves[index];
264 else this.lastMove = null;
266 toggleAnalyze: function() {
267 if (this.mode != "analyze") {
268 // Enter analyze mode:
269 this.gameMode = this.mode; //was not 'analyze'
270 this.mode = "analyze";
271 this.gameCursor = this.cursor;
272 this.gameMoves = JSON.parse(JSON.stringify(this.moves));
273 document.getElementById("analyzeBtn").classList.add("active");
276 // Exit analyze mode:
277 this.mode = this.gameMode ;
278 this.cursor = this.gameCursor;
279 this.moves = this.gameMoves;
280 let fen = this.game.fenStart;
281 if (this.cursor >= 0) {
282 let mv = this.moves[this.cursor];
283 if (!Array.isArray(mv)) mv = [mv];
284 fen = mv[mv.length-1].fen;
286 this.vr = new V(fen);
287 this.incheck = this.vr.getCheckSquares();
288 if (this.cursor >= 0) this.lastMove = this.moves[this.cursor];
289 else this.lastMove = null;
290 document.getElementById("analyzeBtn").classList.remove("active");
293 download: function() {
294 const content = this.getPgn();
295 // Prepare and trigger download link
296 let downloadAnchor = document.getElementById("download");
297 downloadAnchor.setAttribute("download", "game.pgn");
298 downloadAnchor.href =
299 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
300 downloadAnchor.click();
304 pgn += '[Site "vchess.club"]\n';
305 pgn += '[Variant "' + this.game.vname + '"]\n';
306 const gdt = getDate(new Date(this.game.created || Date.now()));
307 pgn += '[Date "' + gdt + '"]\n';
308 pgn += '[White "' + this.game.players[0].name + '"]\n';
309 pgn += '[Black "' + this.game.players[1].name + '"]\n';
310 pgn += '[Fen "' + this.game.fenStart + '"]\n';
311 pgn += '[Result "' + this.game.score + '"]\n';
313 pgn += '[Url "' + params.serverUrl + '/game/' + this.game.id + '"]\n';
314 if (!!this.game.cadence)
315 pgn += '[Cadence "' + this.game.cadence + '"]\n';
317 for (let i = 0; i < this.moves.length; i += 2) {
318 if (i > 0) pgn += " ";
319 // Adjust dots notation for a better display:
320 let fullNotation = getFullNotation(this.moves[i]);
321 if (fullNotation == "...") fullNotation = "..";
322 pgn += (i / 2 + this.firstMoveNumber) + "." + fullNotation;
323 if (i+1 < this.moves.length)
324 pgn += " " + getFullNotation(this.moves[i+1]);
327 for (let i = 0; i < this.moves.length; i += 2) {
328 const moveNumber = i / 2 + this.firstMoveNumber;
329 // Skip "dots move", useless for machine reading:
330 if (this.moves[i].notation != "...") {
331 pgn += moveNumber + ".w " +
332 getFullNotation(this.moves[i], "unambiguous") + "\n";
334 if (i+1 < this.moves.length) {
335 pgn += moveNumber + ".b " +
336 getFullNotation(this.moves[i+1], "unambiguous") + "\n";
341 showEndgameMsg: function(message) {
342 this.endgameMessage = message;
343 document.getElementById("modalEog").checked = true;
345 runAutoplay: function() {
347 this.autoplay = false;
348 if (this.stackToPlay.length > 0)
349 // Move(s) arrived in-between
350 this.play(this.stackToPlay.pop(), "received");
352 else if (this.cursor < this.moves.length - 1) {
353 this.autoplay = true;
354 this.play(null, null, null, "autoplay");
357 // Animate an elementary move
358 animateMove: function(move, callback) {
359 let startSquare = document.getElementById(getSquareId(move.start));
360 if (!startSquare) return; //shouldn't happen but...
361 let endSquare = document.getElementById(getSquareId(move.end));
362 let rectStart = startSquare.getBoundingClientRect();
363 let rectEnd = endSquare.getBoundingClientRect();
365 x: rectEnd.x - rectStart.x,
366 y: rectEnd.y - rectStart.y
368 let movingPiece = document.querySelector(
369 "#" + getSquareId(move.start) + " > img.piece"
371 // For some unknown reasons Opera get "movingPiece == null" error
372 // TODO: is it calling 'animate()' twice ? One extra time ?
373 if (!movingPiece) return;
374 const squares = document.getElementsByClassName("board");
375 for (let i = 0; i < squares.length; i++) {
376 let square = squares.item(i);
377 if (square.id != getSquareId(move.start))
378 // HACK for animation:
379 // (with positive translate, image slides "under background")
380 square.style.zIndex = "-1";
382 movingPiece.style.transform =
383 "translate(" + translation.x + "px," + translation.y + "px)";
384 movingPiece.style.transitionDuration = "0.25s";
385 movingPiece.style.zIndex = "3000";
387 for (let i = 0; i < squares.length; i++)
388 squares.item(i).style.zIndex = "auto";
389 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
394 emitFenIfAnalyze: function() {
395 if (this.game.mode == "analyze") {
396 let fen = this.game.fenStart;
397 if (!!this.lastMove) {
398 if (Array.isArray(this.lastMove)) {
399 const L = this.lastMove.length;
400 fen = this.lastMove[L-1].fen;
402 else fen = this.lastMove.fen;
404 this.$emit("fenchange", fen);
407 clickSquare: function(square) {
408 // Some variants make use of a single click at specific times:
409 const move = this.vr.doClick(square);
410 if (!!move) this.play(move);
412 // "light": if gotoMove() or gotoEnd()
413 play: function(move, received, light, autoplay) {
414 // Freeze while choices are shown:
415 if (this.$refs["board"].choices.length > 0) return;
416 const navigate = !move;
417 // Forbid navigation during autoplay:
418 if (navigate && this.autoplay && !autoplay) return;
419 // Forbid playing outside analyze mode, except if move is received.
420 // Sufficient condition because Board already knows which turn it is.
422 this.mode != "analyze" &&
425 (this.game.score != "*" || this.cursor < this.moves.length - 1)
430 if (this.autoplay || this.inPlay) {
431 // Received moves while autoplaying are stacked,
432 // and in observed games they could arrive too fast:
433 this.stackToPlay.unshift(move);
437 if (this.mode == "analyze") this.toggleAnalyze();
438 if (this.cursor < this.moves.length - 1)
439 // To play a received move, cursor must be at the end of the game:
442 // The board may show some the possible moves: (TODO: bad solution)
443 this.$refs["board"].resetCurrentAttempt();
444 const playSubmove = (smove) => {
445 smove.notation = this.vr.getNotation(smove);
446 smove.unambiguous = V.GetUnambiguousNotation(smove);
448 if (this.inMultimove && !!this.lastMove) {
449 if (!Array.isArray(this.lastMove))
450 this.lastMove = [this.lastMove, smove];
451 else this.lastMove.push(smove);
453 // Is opponent (or me) in check?
454 this.incheck = this.vr.getCheckSquares();
455 if (this.incheck.length > 0) smove.notation += "+";
456 if (!this.inMultimove) {
458 this.lastMove = smove;
459 // Condition is "!navigate" but we mean "!this.autoplay"
461 if (this.cursor < this.moves.length - 1)
462 this.moves = this.moves.slice(0, this.cursor + 1);
463 this.moves.push(smove);
465 this.inMultimove = true; //potentially
467 } else if (!navigate) {
468 // Already in the middle of a multi-move
469 const L = this.moves.length;
470 if (!Array.isArray(this.moves[L-1]))
471 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
472 else this.moves[L-1].push(smove);
475 const playMove = () => {
477 ["all", "highlight"].includes(V.ShowMoves) &&
478 (this.autoplay || !!received)
480 if (!Array.isArray(move)) move = [move];
483 const initurn = this.vr.turn;
484 (function executeMove() {
485 const smove = move[moveIdx++];
486 // NOTE: condition "smove.start.x >= 0" required for Dynamo,
487 // because second move may be empty.
488 if (animate && smove.start.x >= 0) {
489 self.animateMove(smove, () => {
491 if (moveIdx < move.length) setTimeout(executeMove, 500);
492 else afterMove(smove, initurn);
496 if (moveIdx < move.length) executeMove();
497 else afterMove(smove, initurn);
501 const computeScore = () => {
502 const score = this.vr.getCurrentScore();
504 if (["1-0", "0-1"].includes(score)) {
505 if (Array.isArray(this.lastMove)) {
506 const L = this.lastMove.length;
507 this.lastMove[L - 1].notation += "#";
509 else this.lastMove.notation += "#";
512 if (score != "*" && ["analyze", "versus"].includes(this.mode)) {
513 const message = getScoreMessage(score);
514 // Show score on screen
515 this.showEndgameMsg(score + " . " + this.st.tr[message]);
519 const afterMove = (smove, initurn) => {
520 if (this.vr.turn != initurn) {
521 // Turn has changed: move is complete
523 // NOTE: only FEN of last sub-move is required (=> setting it here)
524 smove.fen = this.vr.getFen();
525 this.emitFenIfAnalyze();
526 this.inMultimove = false;
527 this.score = computeScore();
529 if (this.cursor < this.moves.length - 1)
530 setTimeout(() => this.play(null, null, null, "autoplay"), 1000);
532 this.autoplay = false;
533 if (this.stackToPlay.length > 0)
534 // Move(s) arrived in-between
535 this.play(this.stackToPlay.pop(), "received");
538 if (this.mode != "analyze" && !navigate) {
540 // Post-processing (e.g. computer play).
541 const L = this.moves.length;
542 // NOTE: always emit the score, even in unfinished
543 this.$emit("newmove", this.moves[L-1], { score: this.score });
546 if (this.stackToPlay.length > 0)
547 // Move(s) arrived in-between
548 this.play(this.stackToPlay.pop(), "received");
553 // NOTE: navigate and received are mutually exclusive
555 // The move to navigate to is necessarily full:
556 if (this.cursor == this.moves.length - 1) return; //no more moves
557 move = this.moves[this.cursor + 1];
558 if (!this.autoplay) {
559 // Just play the move:
560 if (!Array.isArray(move)) move = [move];
561 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
563 this.lastMove = move;
564 this.incheck = this.vr.getCheckSquares();
565 this.score = computeScore();
566 this.emitFenIfAnalyze();
574 cancelCurrentMultimove: function() {
575 const L = this.moves.length;
576 let move = this.moves[L-1];
577 if (!Array.isArray(move)) move = [move];
578 for (let i = move.length - 1; i >= 0; i--) this.vr.undo(move[i]);
581 this.inMultimove = false;
583 cancelLastMove: function() {
584 // The last played move was canceled (corr game)
588 // "light": if gotoMove() or gotoBegin()
589 undo: function(move, light) {
590 // Freeze while choices are shown:
591 if (this.$refs["board"].choices.length > 0 || this.autoplay) return;
592 this.$refs["board"].resetCurrentAttempt();
593 if (this.inMultimove) {
594 this.cancelCurrentMultimove();
595 this.incheck = this.vr.getCheckSquares();
599 this.moves.length > 0 && this.moves[0].notation == "..."
602 if (this.cursor < minCursor) return; //no more moves
603 move = this.moves[this.cursor];
605 this.$refs["board"].resetCurrentAttempt();
606 undoMove(move, this.vr);
607 if (light) this.cursor--;
609 this.positionCursorTo(this.cursor - 1);
610 this.incheck = this.vr.getCheckSquares();
611 this.emitFenIfAnalyze();
615 gotoMove: function(index) {
616 if (this.$refs["board"].choices.length > 0 || this.autoplay) return;
617 this.$refs["board"].resetCurrentAttempt();
618 if (this.inMultimove) this.cancelCurrentMultimove();
619 if (index == this.cursor) return;
620 if (index < this.cursor) {
621 while (this.cursor > index)
622 this.undo(null, null, "light");
625 // index > this.cursor)
626 while (this.cursor < index)
627 this.play(null, null, "light");
629 // NOTE: next line also re-assign cursor, but it's very light
630 this.positionCursorTo(index);
631 this.incheck = this.vr.getCheckSquares();
632 this.emitFenIfAnalyze();
634 gotoBegin: function() {
635 if (this.$refs["board"].choices.length > 0 || this.autoplay) return;
636 this.$refs["board"].resetCurrentAttempt();
637 if (this.inMultimove) this.cancelCurrentMultimove();
639 this.moves.length > 0 && this.moves[0].notation == "..."
642 while (this.cursor >= minCursor) this.undo(null, null, "light");
643 this.lastMove = (minCursor == 1 ? this.moves[0] : null);
644 this.incheck = this.vr.getCheckSquares();
645 this.emitFenIfAnalyze();
647 gotoEnd: function() {
648 if (this.$refs["board"].choices.length > 0 || this.autoplay) return;
649 this.$refs["board"].resetCurrentAttempt();
650 if (this.cursor == this.moves.length - 1) return;
651 this.gotoMove(this.moves.length - 1);
652 this.emitFenIfAnalyze();
655 if (this.$refs["board"].choices.length > 0) return;
656 this.orientation = V.GetOppCol(this.orientation);
662 <style lang="sass" scoped>
663 [type="checkbox"]#modalEog+div .card
677 display: inline-block
691 background-color: #FACF8C
696 @media screen and (max-width: 767px)
705 // TODO: later, maybe, allow movesList of variable width
706 // or e.g. between 250 and 350px (but more complicated)
712 @media screen and (max-width: 767px)