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"
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...
69 // attention play undo pendant l'autoplay !!
71 import Board from "@/components/Board.vue";
72 import MoveList from "@/components/MoveList.vue";
73 import params from "@/parameters";
74 import { store } from "@/store";
75 import { getSquareId } from "@/utils/squareId";
76 import { getDate } from "@/utils/datetime";
77 import { processModalClick } from "@/utils/modalClick";
78 import { getScoreMessage } from "@/utils/scoring";
79 import { getFullNotation } from "@/utils/notation";
80 import { undoMove } from "@/utils/playUndo";
91 // NOTE: all following variables must be reset at the beginning of a game
92 vr: null, //VariantRules object, game state
96 score: "*", //'*' means 'unfinished'
98 cursor: -1, //index of the move just played
100 firstMoveNumber: 0, //for printing
101 incheck: [], //for Board
110 if (!this.vr) return "";
111 if (this.vr.showMoves != "all") {
113 (this.vr.turn == 'w' ? "White" : "Black") + " to move"];
115 // Cannot flip: racing king or circular chess
117 this.vr.movesCount == 0 && this.game.mycolor == "w"
118 ? this.st.tr["It's your turn!"]
122 showFen: function() {
124 this.mode == "analyze" &&
125 this.$router.currentRoute.path.indexOf("/analyse") === -1
128 // TODO: is it OK to pass "computed" as properties?
129 // Also, some are seemingly not recomputed when vr is initialized.
130 showMoves: function() {
131 return this.game.score != "*"
133 : (!!this.vr ? this.vr.showMoves : "none");
135 showTurn: function() {
137 this.game.score == '*' &&
138 !!this.vr && (this.vr.showMoves != "all" || !this.vr.canFlip)
141 canAnalyze: function() {
143 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 != "*" ||
153 (!!this.vr && this.vr.showMoves == "all")
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 resetArrows: function() {
206 // TODO: make arrows scale with board, and remove this
207 this.$refs["board"].cancelResetArrows();
209 showRules: function() {
210 // The button is here only on Game page:
211 document.getElementById("modalRules").checked = true;
213 re_setVariables: function(game) {
214 if (!game) game = this.game; //in case of...
215 this.endgameMessage = "";
216 // "w": default orientation for observed games
217 this.orientation = game.mycolor || "w";
218 this.mode = game.mode || game.type; //TODO: merge...
219 this.moves = JSON.parse(JSON.stringify(game.moves || []));
220 // Post-processing: decorate each move with notation and FEN
221 this.vr = new V(game.fenStart);
222 const parsedFen = V.ParseFen(game.fenStart);
223 const firstMoveColor = parsedFen.turn;
224 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2) + 1;
225 let L = this.moves.length;
230 this.moves.forEach((move,idx) => {
231 // Strategy working also for multi-moves:
232 if (!Array.isArray(move)) move = [move];
233 const Lm = move.length;
234 move.forEach((m,idxM) => {
235 m.notation = this.vr.getNotation(m);
236 m.unambiguous = V.GetUnambiguousNotation(m);
238 const checkSquares = this.vr.getCheckSquares();
239 if (checkSquares.length > 0) m.notation += "+";
240 if (idxM == Lm - 1) m.fen = this.vr.getFen();
241 if (idx == L - 1 && idxM == Lm - 1) {
242 this.incheck = checkSquares;
243 this.score = this.vr.getCurrentScore();
244 if (["1-0", "0-1"].includes(this.score)) m.notation += "#";
248 if (firstMoveColor == "b") {
249 // 'start' & 'end' is required for Board component
253 start: { x: -1, y: -1 },
254 end: { x: -1, y: -1 },
259 this.positionCursorTo(L - 1);
261 positionCursorTo: function(index) {
263 // Note: last move in moves array might be a multi-move
264 if (index >= 0) this.lastMove = this.moves[index];
265 else this.lastMove = null;
267 toggleAnalyze: function() {
268 if (this.mode != "analyze") {
269 // Enter analyze mode:
270 this.gameMode = this.mode; //was not 'analyze'
271 this.mode = "analyze";
272 this.gameCursor = this.cursor;
273 this.gameMoves = JSON.parse(JSON.stringify(this.moves));
274 document.getElementById("analyzeBtn").classList.add("active");
277 // Exit analyze mode:
278 this.mode = this.gameMode ;
279 this.cursor = this.gameCursor;
280 this.moves = this.gameMoves;
281 let fen = this.game.fenStart;
282 if (this.cursor >= 0) {
283 let mv = this.moves[this.cursor];
284 if (!Array.isArray(mv)) mv = [mv];
285 fen = mv[mv.length-1].fen;
287 this.vr = new V(fen);
288 this.incheck = this.vr.getCheckSquares();
289 if (this.cursor >= 0) this.lastMove = this.moves[this.cursor];
290 else this.lastMove = null;
291 document.getElementById("analyzeBtn").classList.remove("active");
294 download: function() {
295 const content = this.getPgn();
296 // Prepare and trigger download link
297 let downloadAnchor = document.getElementById("download");
298 downloadAnchor.setAttribute("download", "game.pgn");
299 downloadAnchor.href =
300 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
301 downloadAnchor.click();
305 pgn += '[Site "vchess.club"]\n';
306 pgn += '[Variant "' + this.game.vname + '"]\n';
307 const gdt = getDate(new Date(this.game.created || Date.now()));
308 pgn += '[Date "' + gdt + '"]\n';
309 pgn += '[White "' + this.game.players[0].name + '"]\n';
310 pgn += '[Black "' + this.game.players[1].name + '"]\n';
311 pgn += '[Fen "' + this.game.fenStart + '"]\n';
312 pgn += '[Result "' + this.game.score + '"]\n';
314 pgn += '[Url "' + params.serverUrl + '/game/' + this.game.id + '"]\n';
315 if (!!this.game.cadence)
316 pgn += '[Cadence "' + this.game.cadence + '"]\n';
318 for (let i = 0; i < this.moves.length; i += 2) {
319 if (i > 0) pgn += " ";
320 // Adjust dots notation for a better display:
321 let fullNotation = getFullNotation(this.moves[i]);
322 if (fullNotation == "...") fullNotation = "..";
323 pgn += (i / 2 + this.firstMoveNumber) + "." + fullNotation;
324 if (i+1 < this.moves.length)
325 pgn += " " + getFullNotation(this.moves[i+1]);
328 for (let i = 0; i < this.moves.length; i += 2) {
329 const moveNumber = i / 2 + this.firstMoveNumber;
330 // Skip "dots move", useless for machine reading:
331 if (this.moves[i].notation != "...") {
332 pgn += moveNumber + ".w " +
333 getFullNotation(this.moves[i], "unambiguous") + "\n";
335 if (i+1 < this.moves.length) {
336 pgn += moveNumber + ".b " +
337 getFullNotation(this.moves[i+1], "unambiguous") + "\n";
342 showEndgameMsg: function(message) {
343 this.endgameMessage = message;
344 document.getElementById("modalEog").checked = true;
346 runAutoplay: function() {
348 this.autoplay = false;
349 if (this.stackToPlay.length > 0)
350 // Move(s) arrived in-between
351 this.play(this.stackToPlay.pop(), "received");
353 else if (this.cursor < this.moves.length - 1) {
354 this.autoplay = true;
358 // Animate an elementary move
359 animateMove: function(move, callback) {
360 let startSquare = document.getElementById(getSquareId(move.start));
361 if (!startSquare) return; //shouldn't happen but...
362 let endSquare = document.getElementById(getSquareId(move.end));
363 let rectStart = startSquare.getBoundingClientRect();
364 let rectEnd = endSquare.getBoundingClientRect();
366 x: rectEnd.x - rectStart.x,
367 y: rectEnd.y - rectStart.y
369 let movingPiece = document.querySelector(
370 "#" + getSquareId(move.start) + " > img.piece"
372 // For some unknown reasons Opera get "movingPiece == null" error
373 // TODO: is it calling 'animate()' twice ? One extra time ?
374 if (!movingPiece) return;
375 const squares = document.getElementsByClassName("board");
376 for (let i = 0; i < squares.length; i++) {
377 let square = squares.item(i);
378 if (square.id != getSquareId(move.start))
379 // HACK for animation:
380 // (with positive translate, image slides "under background")
381 square.style.zIndex = "-1";
383 movingPiece.style.transform =
384 "translate(" + translation.x + "px," + translation.y + "px)";
385 movingPiece.style.transitionDuration = "0.25s";
386 movingPiece.style.zIndex = "3000";
388 for (let i = 0; i < squares.length; i++)
389 squares.item(i).style.zIndex = "auto";
390 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
395 emitFenIfAnalyze: function() {
396 if (this.game.mode == "analyze") {
397 let fen = this.game.fenStart;
398 if (!!this.lastMove) {
399 if (Array.isArray(this.lastMove)) {
400 const L = this.lastMove.length;
401 fen = this.lastMove[L-1].fen;
403 else fen = this.lastMove.fen;
405 this.$emit("fenchange", fen);
408 clickSquare: function(square) {
409 // Some variants make use of a single click at specific times:
410 const move = this.vr.doClick(square);
411 if (!!move) this.play(move);
413 // "light": if gotoMove() or gotoEnd()
414 play: function(move, received, light) {
415 // Freeze while choices are shown:
416 if (this.$refs["board"].choices.length > 0) return;
417 const navigate = !move;
418 // Forbid playing outside analyze mode, except if move is received.
419 // Sufficient condition because Board already knows which turn it is.
421 this.mode != "analyze" &&
424 (this.game.score != "*" || this.cursor < this.moves.length - 1)
429 if (this.autoplay || this.inPlay) {
430 // Received moves while autoplaying are stacked,
431 // and in observed games they could arrive too fast:
432 this.stackToPlay.unshift(move);
436 if (this.mode == "analyze") this.toggleAnalyze();
437 if (this.cursor < this.moves.length - 1)
438 // To play a received move, cursor must be at the end of the game:
441 // The board may show some the possible moves: (TODO: bad solution)
442 this.$refs["board"].resetCurrentAttempt();
443 const playSubmove = (smove) => {
444 smove.notation = this.vr.getNotation(smove);
445 smove.unambiguous = V.GetUnambiguousNotation(smove);
447 if (this.inMultimove && !!this.lastMove) {
448 if (!Array.isArray(this.lastMove))
449 this.lastMove = [this.lastMove, smove];
450 else this.lastMove.push(smove);
452 // Is opponent (or me) in check?
453 this.incheck = this.vr.getCheckSquares();
454 if (this.incheck.length > 0) smove.notation += "+";
455 if (!this.inMultimove) {
457 this.lastMove = smove;
458 // Condition is "!navigate" but we mean "!this.autoplay"
460 if (this.cursor < this.moves.length - 1)
461 this.moves = this.moves.slice(0, this.cursor + 1);
462 this.moves.push(smove);
464 this.inMultimove = true; //potentially
466 } else if (!navigate) {
467 // Already in the middle of a multi-move
468 const L = this.moves.length;
469 if (!Array.isArray(this.moves[L-1]))
470 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
471 else this.moves[L-1].push(smove);
474 const playMove = () => {
476 ["all", "highlight"].includes(V.ShowMoves) &&
477 (this.autoplay || !!received)
479 if (!Array.isArray(move)) move = [move];
482 const initurn = this.vr.turn;
483 (function executeMove() {
484 const smove = move[moveIdx++];
485 // NOTE: condition "smove.start.x >= 0" required for Dynamo,
486 // because second move may be empty.
487 if (animate && smove.start.x >= 0) {
488 self.animateMove(smove, () => {
490 if (moveIdx < move.length) setTimeout(executeMove, 500);
491 else afterMove(smove, initurn);
495 if (moveIdx < move.length) executeMove();
496 else afterMove(smove, initurn);
500 const computeScore = () => {
501 const score = this.vr.getCurrentScore();
503 if (["1-0", "0-1"].includes(score)) {
504 if (Array.isArray(this.lastMove)) {
505 const L = this.lastMove.length;
506 this.lastMove[L - 1].notation += "#";
508 else this.lastMove.notation += "#";
511 if (score != "*" && ["analyze", "versus"].includes(this.mode)) {
512 const message = getScoreMessage(score);
513 // Show score on screen
514 this.showEndgameMsg(score + " . " + this.st.tr[message]);
518 const afterMove = (smove, initurn) => {
519 if (this.vr.turn != initurn) {
520 // Turn has changed: move is complete
522 // NOTE: only FEN of last sub-move is required (=> setting it here)
523 smove.fen = this.vr.getFen();
524 this.emitFenIfAnalyze();
525 this.inMultimove = false;
526 this.score = computeScore();
528 if (this.cursor < this.moves.length - 1)
529 setTimeout(this.play, 1000);
531 this.autoplay = false;
532 if (this.stackToPlay.length > 0)
533 // Move(s) arrived in-between
534 this.play(this.stackToPlay.pop(), "received");
537 if (this.mode != "analyze" && !navigate) {
539 // Post-processing (e.g. computer play).
540 const L = this.moves.length;
541 // NOTE: always emit the score, even in unfinished
542 this.$emit("newmove", this.moves[L-1], { score: this.score });
545 if (this.stackToPlay.length > 0)
546 // Move(s) arrived in-between
547 this.play(this.stackToPlay.pop(), "received");
552 // NOTE: navigate and received are mutually exclusive
554 // The move to navigate to is necessarily full:
555 if (this.cursor == this.moves.length - 1) return; //no more moves
556 move = this.moves[this.cursor + 1];
557 if (!this.autoplay) {
558 // Just play the move:
559 if (!Array.isArray(move)) move = [move];
560 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
562 this.lastMove = move;
563 this.incheck = this.vr.getCheckSquares();
564 this.score = computeScore();
565 this.emitFenIfAnalyze();
573 cancelCurrentMultimove: function() {
574 const L = this.moves.length;
575 let move = this.moves[L-1];
576 if (!Array.isArray(move)) move = [move];
577 for (let i = move.length - 1; i >= 0; i--) this.vr.undo(move[i]);
580 this.inMultimove = false;
582 cancelLastMove: function() {
583 // The last played move was canceled (corr game)
587 // "light": if gotoMove() or gotoBegin()
588 undo: function(move, light) {
589 // Freeze while choices are shown:
590 if (this.$refs["board"].choices.length > 0) return;
591 this.$refs["board"].resetCurrentAttempt();
592 if (this.inMultimove) {
593 this.cancelCurrentMultimove();
594 this.incheck = this.vr.getCheckSquares();
598 this.moves.length > 0 && this.moves[0].notation == "..."
601 if (this.cursor < minCursor) return; //no more moves
602 move = this.moves[this.cursor];
604 this.$refs["board"].resetCurrentAttempt();
605 undoMove(move, this.vr);
606 if (light) this.cursor--;
608 this.positionCursorTo(this.cursor - 1);
609 this.incheck = this.vr.getCheckSquares();
610 this.emitFenIfAnalyze();
614 gotoMove: function(index) {
615 if (this.$refs["board"].choices.length > 0) return;
616 this.$refs["board"].resetCurrentAttempt();
617 if (this.inMultimove) this.cancelCurrentMultimove();
618 if (index == this.cursor) return;
619 if (index < this.cursor) {
620 while (this.cursor > index)
621 this.undo(null, null, "light");
624 // index > this.cursor)
625 while (this.cursor < index)
626 this.play(null, null, "light");
628 // NOTE: next line also re-assign cursor, but it's very light
629 this.positionCursorTo(index);
630 this.incheck = this.vr.getCheckSquares();
631 this.emitFenIfAnalyze();
633 gotoBegin: function() {
634 if (this.$refs["board"].choices.length > 0) return;
635 this.$refs["board"].resetCurrentAttempt();
636 if (this.inMultimove) this.cancelCurrentMultimove();
638 this.moves.length > 0 && this.moves[0].notation == "..."
641 while (this.cursor >= minCursor) this.undo(null, null, "light");
642 this.lastMove = (minCursor == 1 ? this.moves[0] : null);
643 this.incheck = this.vr.getCheckSquares();
644 this.emitFenIfAnalyze();
646 gotoEnd: function() {
647 if (this.$refs["board"].choices.length > 0) return;
648 this.$refs["board"].resetCurrentAttempt();
649 if (this.cursor == this.moves.length - 1) return;
650 this.gotoMove(this.moves.length - 1);
651 this.emitFenIfAnalyze();
654 if (this.$refs["board"].choices.length > 0) return;
655 this.orientation = V.GetOppCol(this.orientation);
661 <style lang="sass" scoped>
662 [type="checkbox"]#modalEog+div .card
676 display: inline-block
687 background-color: #FACF8C
692 @media screen and (max-width: 767px)
701 // TODO: later, maybe, allow movesList of variable width
702 // or e.g. between 250 and 350px (but more complicated)
708 @media screen and (max-width: 767px)