3 input#modalEog.modal(type="checkbox")
6 data-checkbox="modalEog"
9 label.modal-close(for="modalEog")
10 h3.section {{ endgameMessage }}
17 :analyze="game.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")
46 :canAnalyze="canAnalyze"
47 :canDownload="allowDownloadPGN"
49 :message="game.scoreMsg"
50 :firstNum="firstMoveNumber"
54 @showrules="showRules"
55 @analyze="analyzePosition"
57 @reset-arrows="resetArrows"
63 import Board from "@/components/Board.vue";
64 import MoveList from "@/components/MoveList.vue";
65 import params from "@/parameters";
66 import { store } from "@/store";
67 import { getSquareId } from "@/utils/squareId";
68 import { getDate } from "@/utils/datetime";
69 import { processModalClick } from "@/utils/modalClick";
70 import { getScoreMessage } from "@/utils/scoring";
71 import { getFullNotation } from "@/utils/notation";
72 import { undoMove } from "@/utils/playUndo";
83 // NOTE: all following variables must be reset at the beginning of a game
84 vr: null, //VariantRules object, game state
87 score: "*", //'*' means 'unfinished'
89 cursor: -1, //index of the move just played
91 firstMoveNumber: 0, //for printing
92 incheck: [], //for Board
102 if (!this.vr) return "";
103 if (this.vr.showMoves != "all") {
105 (this.vr.turn == 'w' ? "White" : "Black") + " to move"];
107 // Cannot flip: racing king or circular chess
109 this.vr.movesCount == 0 && this.game.mycolor == "w"
110 ? this.st.tr["It's your turn!"]
114 // TODO: is it OK to pass "computed" as properties?
115 // Also, some are seemingly not recomputed when vr is initialized.
116 showMoves: function() {
117 return this.game.score != "*"
119 : (!!this.vr ? this.vr.showMoves : "none");
121 showTurn: function() {
123 this.game.score == '*' &&
124 !!this.vr && (this.vr.showMoves != "all" || !this.vr.canFlip)
127 canAnalyze: function() {
129 this.game.mode != "analyze" &&
130 !!this.vr && this.vr.canAnalyze
133 canFlip: function() {
134 return !!this.vr && this.vr.canFlip;
136 allowDownloadPGN: function() {
138 this.game.score != "*" ||
139 (!!this.vr && this.vr.showMoves == "all")
143 created: function() {
144 if (!!this.game.fenStart) this.re_setVariables();
146 mounted: function() {
147 if (!("ontouchstart" in window)) {
149 const baseGameDiv = document.getElementById("baseGame");
150 baseGameDiv.tabIndex = 0;
151 baseGameDiv.addEventListener("click", this.focusBg);
152 baseGameDiv.addEventListener("keydown", this.handleKeys);
153 baseGameDiv.addEventListener("wheel", this.handleScroll);
155 document.getElementById("eogDiv")
156 .addEventListener("click", processModalClick);
158 beforeDestroy: function() {
159 if (!!this.autoplayLoop) clearInterval(this.autoplayLoop);
162 focusBg: function() {
163 document.getElementById("baseGame").focus();
165 handleKeys: function(e) {
166 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
185 handleScroll: function(e) {
187 if (e.deltaY < 0) this.undo();
188 else if (e.deltaY > 0) this.play();
190 resetArrows: function() {
191 // TODO: make arrows scale with board, and remove this
192 this.$refs["board"].cancelResetArrows();
194 showRules: function() {
195 //this.$router.push("/variants/" + this.game.vname);
196 window.open("#/variants/" + this.game.vname, "_blank"); //better
198 re_setVariables: function(game) {
199 if (!game) game = this.game; //in case of...
200 this.endgameMessage = "";
201 // "w": default orientation for observed games
202 this.orientation = game.mycolor || "w";
203 this.moves = JSON.parse(JSON.stringify(game.moves || []));
204 // Post-processing: decorate each move with notation and FEN
205 this.vr = new V(game.fenStart);
206 const parsedFen = V.ParseFen(game.fenStart);
207 const firstMoveColor = parsedFen.turn;
208 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2);
209 let L = this.moves.length;
210 this.moves.forEach(move => {
211 // Strategy working also for multi-moves:
212 if (!Array.isArray(move)) move = [move];
213 move.forEach((m,idx) => {
214 m.index = this.vr.movesCount;
215 m.notation = this.vr.getNotation(m);
216 m.unambiguous = V.GetUnambiguousNotation(m);
218 if (idx < L - 1 && this.vr.getCheckSquares(this.vr.turn).length > 0)
222 if (firstMoveColor == "b") {
223 // 'start' & 'end' is required for Board component
225 index: parsedFen.movesCount,
228 start: { x: -1, y: -1 },
229 end: { x: -1, y: -1 },
234 this.positionCursorTo(this.moves.length - 1);
235 this.incheck = this.vr.getCheckSquares(this.vr.turn);
236 const score = this.vr.getCurrentScore();
237 if (L > 0 && this.moves[L - 1].notation != "...") {
238 if (["1-0","0-1"].includes(score)) this.moves[L - 1].notation += "#";
239 else if (this.incheck.length > 0) this.moves[L - 1].notation += "+";
242 positionCursorTo: function(index) {
244 // Caution: last move in moves array might be a multi-move
246 if (Array.isArray(this.moves[index])) {
247 const L = this.moves[index].length;
248 this.lastMove = this.moves[index][L - 1];
250 this.lastMove = this.moves[index];
252 } else this.lastMove = null;
254 analyzePosition: function() {
259 this.vr.getFen().replace(/ /g, "_");
260 if (!!this.game.mycolor) newUrl += "&side=" + this.game.mycolor;
261 window.open("#" + newUrl);
263 download: function() {
264 const content = this.getPgn();
265 // Prepare and trigger download link
266 let downloadAnchor = document.getElementById("download");
267 downloadAnchor.setAttribute("download", "game.pgn");
268 downloadAnchor.href =
269 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
270 downloadAnchor.click();
274 pgn += '[Site "vchess.club"]\n';
275 pgn += '[Variant "' + this.game.vname + '"]\n';
276 const gdt = getDate(new Date(this.game.created || Date.now()));
277 pgn += '[Date "' + gdt + '"]\n';
278 pgn += '[White "' + this.game.players[0].name + '"]\n';
279 pgn += '[Black "' + this.game.players[1].name + '"]\n';
280 pgn += '[Fen "' + this.game.fenStart + '"]\n';
281 pgn += '[Result "' + this.game.score + '"]\n';
282 if (!!this.game.id) {
283 pgn += '[Cadence "' + this.game.cadence + '"]\n';
284 pgn += '[Url "' + params.serverUrl + '/game/' + this.game.id + '"]\n';
287 for (let i = 0; i < this.moves.length; i += 2) {
288 if (i > 0) pgn += " ";
289 // Adjust dots notation for a better display:
290 let fullNotation = getFullNotation(this.moves[i]);
291 if (fullNotation == "...") fullNotation = "..";
292 pgn += (this.moves[i].index / 2 + 1) + "." + fullNotation;
293 if (i+1 < this.moves.length)
294 pgn += " " + getFullNotation(this.moves[i+1]);
297 for (let i = 0; i < this.moves.length; i += 2) {
298 const moveNumber = this.moves[i].index / 2 + 1;
299 // Skip "dots move", useless for machine reading:
300 if (this.moves[i].notation != "...") {
301 pgn += moveNumber + ".w " +
302 getFullNotation(this.moves[i], "unambiguous") + "\n";
304 if (i+1 < this.moves.length) {
305 pgn += moveNumber + ".b " +
306 getFullNotation(this.moves[i+1], "unambiguous") + "\n";
311 showEndgameMsg: function(message) {
312 this.endgameMessage = message;
313 document.getElementById("modalEog").checked = true;
315 runAutoplay: function() {
316 const infinitePlay = () => {
317 if (this.cursor == this.moves.length - 1) {
318 clearInterval(this.autoplayLoop);
319 this.autoplayLoop = null;
320 this.autoplay = false;
323 if (this.inPlay || this.inMultimove)
329 this.autoplay = false;
330 clearInterval(this.autoplayLoop);
331 this.autoplayLoop = null;
333 this.autoplay = true;
337 this.autoplayLoop = setInterval(infinitePlay, 1500);
339 // Small delay otherwise the first move is played too fast
344 // Animate an elementary move
345 animateMove: function(move, callback) {
346 let startSquare = document.getElementById(getSquareId(move.start));
347 if (!startSquare) return; //shouldn't happen but...
348 let endSquare = document.getElementById(getSquareId(move.end));
349 let rectStart = startSquare.getBoundingClientRect();
350 let rectEnd = endSquare.getBoundingClientRect();
352 x: rectEnd.x - rectStart.x,
353 y: rectEnd.y - rectStart.y
355 let movingPiece = document.querySelector(
356 "#" + getSquareId(move.start) + " > img.piece"
358 // For some unknown reasons Opera get "movingPiece == null" error
359 // TODO: is it calling 'animate()' twice ? One extra time ?
360 if (!movingPiece) return;
361 const squares = document.getElementsByClassName("board");
362 for (let i = 0; i < squares.length; i++) {
363 let square = squares.item(i);
364 if (square.id != getSquareId(move.start))
365 // HACK for animation:
366 // (with positive translate, image slides "under background")
367 square.style.zIndex = "-1";
369 movingPiece.style.transform =
370 "translate(" + translation.x + "px," + translation.y + "px)";
371 movingPiece.style.transitionDuration = "0.25s";
372 movingPiece.style.zIndex = "3000";
374 for (let i = 0; i < squares.length; i++)
375 squares.item(i).style.zIndex = "auto";
376 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
381 emitFenIfAnalyze: function() {
382 if (this.game.mode == "analyze") {
385 !!this.lastMove ? this.lastMove.fen : this.game.fenStart
389 clickSquare: function(square) {
390 // Some variants make use of a single click at specific times:
391 const move = this.vr.doClick(square);
392 if (!!move) this.play(move);
394 // "light": if gotoMove() or gotoEnd()
395 play: function(move, received, light, noemit) {
396 // Freeze while choices are shown:
397 if (this.$refs["board"].choices.length > 0) return;
398 // The board may show some the possible moves: (TODO: bad solution)
399 this.$refs["board"].resetCurrentAttempt();
402 // Received moves in observed games can arrive too fast:
403 this.stackToPlay.unshift(move);
408 const navigate = !move;
409 const playSubmove = (smove) => {
410 smove.notation = this.vr.getNotation(smove);
411 smove.unambiguous = V.GetUnambiguousNotation(smove);
413 this.lastMove = smove;
414 // Is opponent (or me) in check?
415 this.incheck = this.vr.getCheckSquares(this.vr.turn);
416 if (!this.inMultimove) {
417 // Condition is "!navigate" but we mean "!this.autoplay"
419 if (this.cursor < this.moves.length - 1)
420 this.moves = this.moves.slice(0, this.cursor + 1);
421 this.moves.push(smove);
423 this.inMultimove = true; //potentially
425 } else if (!navigate) {
426 // Already in the middle of a multi-move
427 const L = this.moves.length;
428 if (!Array.isArray(this.moves[L-1]))
429 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
430 else this.moves[L-1].push(smove);
433 const playMove = () => {
435 ["all", "highlight"].includes(V.ShowMoves) &&
436 (this.autoplay || !!received)
438 if (!Array.isArray(move)) move = [move];
441 const initurn = this.vr.turn;
442 (function executeMove() {
443 const smove = move[moveIdx++];
444 // NOTE: condition "smove.start.x >= 0" required for Dynamo,
445 // because second move may be empty.
446 if (animate && smove.start.x >= 0) {
447 self.animateMove(smove, () => {
449 if (moveIdx < move.length)
450 setTimeout(executeMove, 500);
451 else afterMove(smove, initurn);
455 if (moveIdx < move.length) executeMove();
456 else afterMove(smove, initurn);
460 const computeScore = () => {
461 const score = this.vr.getCurrentScore();
463 if (["1-0","0-1"].includes(score)) this.lastMove.notation += "#";
464 else if (this.incheck.length > 0) this.lastMove.notation += "+";
466 if (score != "*" && this.game.mode == "analyze") {
467 const message = getScoreMessage(score);
468 // Just show score on screen (allow undo)
469 this.showEndgameMsg(score + " . " + this.st.tr[message]);
473 const afterMove = (smove, initurn) => {
474 if (this.vr.turn != initurn) {
475 // Turn has changed: move is complete
477 // NOTE: only FEN of last sub-move is required (=> setting it here)
478 smove.fen = this.vr.getFen();
479 this.emitFenIfAnalyze();
480 this.inMultimove = false;
481 this.score = computeScore();
482 if (this.game.mode != "analyze" && !navigate) {
484 // Post-processing (e.g. computer play).
485 const L = this.moves.length;
486 // NOTE: always emit the score, even in unfinished,
487 // to tell Game::processMove() that it's not a received move.
488 this.$emit("newmove", this.moves[L-1], { score: this.score });
491 if (this.stackToPlay.length > 0)
492 // Move(s) arrived in-between
493 this.play(this.stackToPlay.pop(), received, light, noemit);
498 // NOTE: navigate and received are mutually exclusive
500 // The move to navigate to is necessarily full:
501 if (this.cursor == this.moves.length - 1) return; //no more moves
502 move = this.moves[this.cursor + 1];
503 if (!this.autoplay) {
504 // Just play the move:
505 if (!Array.isArray(move)) move = [move];
506 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
508 this.lastMove = move[move.length-1];
509 this.incheck = this.vr.getCheckSquares(this.vr.turn);
510 this.score = computeScore();
511 this.emitFenIfAnalyze();
517 // Forbid playing outside analyze mode, except if move is received.
518 // Sufficient condition because Board already knows which turn it is.
520 this.game.mode != "analyze" &&
523 (this.game.score != "*" || this.cursor < this.moves.length - 1)
527 // To play a received move, cursor must be at the end of the game:
528 if (received && this.cursor < this.moves.length - 1)
532 cancelCurrentMultimove: function() {
533 const L = this.moves.length;
534 let move = this.moves[L-1];
535 if (!Array.isArray(move)) move = [move];
536 for (let i = move.length - 1; i >= 0; i--) this.vr.undo(move[i]);
539 this.inMultimove = false;
541 cancelLastMove: function() {
542 // The last played move was canceled (corr game)
546 // "light": if gotoMove() or gotoBegin()
547 undo: function(move, light) {
548 // Freeze while choices are shown:
549 if (this.$refs["board"].choices.length > 0) return;
550 this.$refs["board"].resetCurrentAttempt();
551 if (this.inMultimove) {
552 this.cancelCurrentMultimove();
553 this.incheck = this.vr.getCheckSquares(this.vr.turn);
557 this.moves.length > 0 && this.moves[0].notation == "..."
560 if (this.cursor < minCursor) return; //no more moves
561 move = this.moves[this.cursor];
563 this.$refs["board"].resetCurrentAttempt();
564 undoMove(move, this.vr);
565 if (light) this.cursor--;
567 this.positionCursorTo(this.cursor - 1);
568 this.incheck = this.vr.getCheckSquares(this.vr.turn);
569 this.emitFenIfAnalyze();
573 gotoMove: function(index) {
574 if (this.$refs["board"].choices.length > 0) return;
575 this.$refs["board"].resetCurrentAttempt();
576 if (this.inMultimove) this.cancelCurrentMultimove();
577 if (index == this.cursor) return;
578 if (index < this.cursor) {
579 while (this.cursor > index)
580 this.undo(null, null, "light");
583 // index > this.cursor)
584 while (this.cursor < index)
585 this.play(null, null, "light");
587 // NOTE: next line also re-assign cursor, but it's very light
588 this.positionCursorTo(index);
589 this.incheck = this.vr.getCheckSquares(this.vr.turn);
590 this.emitFenIfAnalyze();
592 gotoBegin: function() {
593 if (this.$refs["board"].choices.length > 0) return;
594 this.$refs["board"].resetCurrentAttempt();
595 if (this.inMultimove) this.cancelCurrentMultimove();
597 this.moves.length > 0 && this.moves[0].notation == "..."
600 while (this.cursor >= minCursor) this.undo(null, null, "light");
601 this.lastMove = (minCursor == 1 ? this.moves[0] : null);
602 this.incheck = this.vr.getCheckSquares(this.vr.turn);
603 this.emitFenIfAnalyze();
605 gotoEnd: function() {
606 if (this.$refs["board"].choices.length > 0) return;
607 this.$refs["board"].resetCurrentAttempt();
608 if (this.cursor == this.moves.length - 1) return;
609 this.gotoMove(this.moves.length - 1);
610 this.emitFenIfAnalyze();
613 if (this.$refs["board"].choices.length > 0) return;
614 this.orientation = V.GetOppCol(this.orientation);
620 <style lang="sass" scoped>
621 [type="checkbox"]#modalEog+div .card
634 display: inline-block
645 background-color: #FACF8C
650 @media screen and (max-width: 767px)
659 // TODO: later, maybe, allow movesList of variable width
660 // or e.g. between 250 and 350px (but more complicated)
666 @media screen and (max-width: 767px)