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) + 1;
209 let L = this.moves.length;
210 this.moves.forEach((move,idx) => {
211 // Strategy working also for multi-moves:
212 if (!Array.isArray(move)) move = [move];
213 const Lm = move.length;
214 move.forEach((m,idxM) => {
215 m.notation = this.vr.getNotation(m);
216 m.unambiguous = V.GetUnambiguousNotation(m);
218 const checkSquares = this.vr.getCheckSquares();
219 if (checkSquares.length > 0) m.notation += "+";
220 if (idx == L - 1 && idxM == Lm - 1) {
221 this.incheck = checkSquares;
222 const score = this.vr.getCurrentScore();
223 if (["1-0", "0-1"].includes(score)) m.notation += "#";
227 if (firstMoveColor == "b") {
228 // 'start' & 'end' is required for Board component
232 start: { x: -1, y: -1 },
233 end: { x: -1, y: -1 },
238 this.positionCursorTo(L - 1);
240 positionCursorTo: function(index) {
242 // Note: last move in moves array might be a multi-move
243 if (index >= 0) this.lastMove = this.moves[index];
244 else this.lastMove = null;
246 analyzePosition: function() {
251 this.vr.getFen().replace(/ /g, "_");
252 if (!!this.game.mycolor) newUrl += "&side=" + this.game.mycolor;
253 window.open("#" + newUrl);
255 download: function() {
256 const content = this.getPgn();
257 // Prepare and trigger download link
258 let downloadAnchor = document.getElementById("download");
259 downloadAnchor.setAttribute("download", "game.pgn");
260 downloadAnchor.href =
261 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
262 downloadAnchor.click();
266 pgn += '[Site "vchess.club"]\n';
267 pgn += '[Variant "' + this.game.vname + '"]\n';
268 const gdt = getDate(new Date(this.game.created || Date.now()));
269 pgn += '[Date "' + gdt + '"]\n';
270 pgn += '[White "' + this.game.players[0].name + '"]\n';
271 pgn += '[Black "' + this.game.players[1].name + '"]\n';
272 pgn += '[Fen "' + this.game.fenStart + '"]\n';
273 pgn += '[Result "' + this.game.score + '"]\n';
275 pgn += '[Url "' + params.serverUrl + '/game/' + this.game.id + '"]\n';
276 if (!!this.game.cadence)
277 pgn += '[Cadence "' + this.game.cadence + '"]\n';
279 for (let i = 0; i < this.moves.length; i += 2) {
280 if (i > 0) pgn += " ";
281 // Adjust dots notation for a better display:
282 let fullNotation = getFullNotation(this.moves[i]);
283 if (fullNotation == "...") fullNotation = "..";
284 pgn += (i / 2 + this.firstMoveNumber) + "." + fullNotation;
285 if (i+1 < this.moves.length)
286 pgn += " " + getFullNotation(this.moves[i+1]);
289 for (let i = 0; i < this.moves.length; i += 2) {
290 const moveNumber = i / 2 + this.firstMoveNumber;
291 // Skip "dots move", useless for machine reading:
292 if (this.moves[i].notation != "...") {
293 pgn += moveNumber + ".w " +
294 getFullNotation(this.moves[i], "unambiguous") + "\n";
296 if (i+1 < this.moves.length) {
297 pgn += moveNumber + ".b " +
298 getFullNotation(this.moves[i+1], "unambiguous") + "\n";
303 showEndgameMsg: function(message) {
304 this.endgameMessage = message;
305 document.getElementById("modalEog").checked = true;
307 runAutoplay: function() {
308 const infinitePlay = () => {
309 if (this.cursor == this.moves.length - 1) {
310 clearInterval(this.autoplayLoop);
311 this.autoplayLoop = null;
312 this.autoplay = false;
315 if (this.inPlay || this.inMultimove)
321 this.autoplay = false;
322 clearInterval(this.autoplayLoop);
323 this.autoplayLoop = null;
325 this.autoplay = true;
329 this.autoplayLoop = setInterval(infinitePlay, 1500);
331 // Small delay otherwise the first move is played too fast
336 // Animate an elementary move
337 animateMove: function(move, callback) {
338 let startSquare = document.getElementById(getSquareId(move.start));
339 if (!startSquare) return; //shouldn't happen but...
340 let endSquare = document.getElementById(getSquareId(move.end));
341 let rectStart = startSquare.getBoundingClientRect();
342 let rectEnd = endSquare.getBoundingClientRect();
344 x: rectEnd.x - rectStart.x,
345 y: rectEnd.y - rectStart.y
347 let movingPiece = document.querySelector(
348 "#" + getSquareId(move.start) + " > img.piece"
350 // For some unknown reasons Opera get "movingPiece == null" error
351 // TODO: is it calling 'animate()' twice ? One extra time ?
352 if (!movingPiece) return;
353 const squares = document.getElementsByClassName("board");
354 for (let i = 0; i < squares.length; i++) {
355 let square = squares.item(i);
356 if (square.id != getSquareId(move.start))
357 // HACK for animation:
358 // (with positive translate, image slides "under background")
359 square.style.zIndex = "-1";
361 movingPiece.style.transform =
362 "translate(" + translation.x + "px," + translation.y + "px)";
363 movingPiece.style.transitionDuration = "0.25s";
364 movingPiece.style.zIndex = "3000";
366 for (let i = 0; i < squares.length; i++)
367 squares.item(i).style.zIndex = "auto";
368 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
373 emitFenIfAnalyze: function() {
374 if (this.game.mode == "analyze") {
375 let fen = this.game.fenStart;
376 if (!!this.lastMove) {
377 if (Array.isArray(this.lastMove)) {
378 const L = this.lastMove.length;
379 fen = this.lastMove[L-1].fen;
381 else fen = this.lastMove.fen;
383 this.$emit("fenchange", fen);
386 clickSquare: function(square) {
387 // Some variants make use of a single click at specific times:
388 const move = this.vr.doClick(square);
389 if (!!move) this.play(move);
391 // "light": if gotoMove() or gotoEnd()
392 play: function(move, received, light, noemit) {
393 // Freeze while choices are shown:
394 if (this.$refs["board"].choices.length > 0) return;
395 // The board may show some the possible moves: (TODO: bad solution)
396 this.$refs["board"].resetCurrentAttempt();
399 // Received moves in observed games can arrive too fast:
400 this.stackToPlay.unshift(move);
405 const navigate = !move;
406 const playSubmove = (smove) => {
407 smove.notation = this.vr.getNotation(smove);
408 smove.unambiguous = V.GetUnambiguousNotation(smove);
410 if (!!this.lastMove) {
411 if (!Array.isArray(this.lastMove))
412 this.lastMove = [this.lastMove, smove];
413 else this.lastMove.push(smove);
415 // Is opponent (or me) in check?
416 this.incheck = this.vr.getCheckSquares();
417 if (this.incheck.length > 0) smove.notation += "+";
418 if (!this.inMultimove) {
420 this.lastMove = smove;
421 // Condition is "!navigate" but we mean "!this.autoplay"
423 if (this.cursor < this.moves.length - 1)
424 this.moves = this.moves.slice(0, this.cursor + 1);
425 this.moves.push(smove);
427 this.inMultimove = true; //potentially
429 } else if (!navigate) {
430 // Already in the middle of a multi-move
431 const L = this.moves.length;
432 if (!Array.isArray(this.moves[L-1]))
433 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
434 else this.moves[L-1].push(smove);
437 const playMove = () => {
439 ["all", "highlight"].includes(V.ShowMoves) &&
440 (this.autoplay || !!received)
442 if (!Array.isArray(move)) move = [move];
445 const initurn = this.vr.turn;
446 (function executeMove() {
447 const smove = move[moveIdx++];
448 // NOTE: condition "smove.start.x >= 0" required for Dynamo,
449 // because second move may be empty.
450 if (animate && smove.start.x >= 0) {
451 self.animateMove(smove, () => {
453 if (moveIdx < move.length)
454 setTimeout(executeMove, 500);
455 else afterMove(smove, initurn);
459 if (moveIdx < move.length) executeMove();
460 else afterMove(smove, initurn);
464 const computeScore = () => {
465 const score = this.vr.getCurrentScore();
467 if (["1-0","0-1"].includes(score)) {
468 if (Array.isArray(this.lastMove)) {
469 const L = this.lastMove.length;
470 this.lastMove[L - 1].notation += "#";
472 else this.lastMove.notation += "#";
475 if (score != "*" && this.game.mode == "analyze") {
476 const message = getScoreMessage(score);
477 // Just show score on screen (allow undo)
478 this.showEndgameMsg(score + " . " + this.st.tr[message]);
482 const afterMove = (smove, initurn) => {
483 if (this.vr.turn != initurn) {
484 // Turn has changed: move is complete
486 // NOTE: only FEN of last sub-move is required (=> setting it here)
487 smove.fen = this.vr.getFen();
488 this.emitFenIfAnalyze();
489 this.inMultimove = false;
490 this.score = computeScore();
491 if (this.game.mode != "analyze" && !navigate) {
493 // Post-processing (e.g. computer play).
494 const L = this.moves.length;
495 // NOTE: always emit the score, even in unfinished,
496 // to tell Game::processMove() that it's not a received move.
497 this.$emit("newmove", this.moves[L-1], { score: this.score });
500 if (this.stackToPlay.length > 0)
501 // Move(s) arrived in-between
502 this.play(this.stackToPlay.pop(), received, light, noemit);
507 // NOTE: navigate and received are mutually exclusive
509 // The move to navigate to is necessarily full:
510 if (this.cursor == this.moves.length - 1) return; //no more moves
511 move = this.moves[this.cursor + 1];
512 if (!this.autoplay) {
513 // Just play the move:
514 if (!Array.isArray(move)) move = [move];
515 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
517 this.lastMove = move;
518 this.incheck = this.vr.getCheckSquares();
519 this.score = computeScore();
520 this.emitFenIfAnalyze();
526 // Forbid playing outside analyze mode, except if move is received.
527 // Sufficient condition because Board already knows which turn it is.
529 this.game.mode != "analyze" &&
532 (this.game.score != "*" || this.cursor < this.moves.length - 1)
536 // To play a received move, cursor must be at the end of the game:
537 if (received && this.cursor < this.moves.length - 1)
541 cancelCurrentMultimove: function() {
542 const L = this.moves.length;
543 let move = this.moves[L-1];
544 if (!Array.isArray(move)) move = [move];
545 for (let i = move.length - 1; i >= 0; i--) this.vr.undo(move[i]);
548 this.inMultimove = false;
550 cancelLastMove: function() {
551 // The last played move was canceled (corr game)
555 // "light": if gotoMove() or gotoBegin()
556 undo: function(move, light) {
557 // Freeze while choices are shown:
558 if (this.$refs["board"].choices.length > 0) return;
559 this.$refs["board"].resetCurrentAttempt();
560 if (this.inMultimove) {
561 this.cancelCurrentMultimove();
562 this.incheck = this.vr.getCheckSquares();
566 this.moves.length > 0 && this.moves[0].notation == "..."
569 if (this.cursor < minCursor) return; //no more moves
570 move = this.moves[this.cursor];
572 this.$refs["board"].resetCurrentAttempt();
573 undoMove(move, this.vr);
574 if (light) this.cursor--;
576 this.positionCursorTo(this.cursor - 1);
577 this.incheck = this.vr.getCheckSquares();
578 this.emitFenIfAnalyze();
582 gotoMove: function(index) {
583 if (this.$refs["board"].choices.length > 0) return;
584 this.$refs["board"].resetCurrentAttempt();
585 if (this.inMultimove) this.cancelCurrentMultimove();
586 if (index == this.cursor) return;
587 if (index < this.cursor) {
588 while (this.cursor > index)
589 this.undo(null, null, "light");
592 // index > this.cursor)
593 while (this.cursor < index)
594 this.play(null, null, "light");
596 // NOTE: next line also re-assign cursor, but it's very light
597 this.positionCursorTo(index);
598 this.incheck = this.vr.getCheckSquares();
599 this.emitFenIfAnalyze();
601 gotoBegin: function() {
602 if (this.$refs["board"].choices.length > 0) return;
603 this.$refs["board"].resetCurrentAttempt();
604 if (this.inMultimove) this.cancelCurrentMultimove();
606 this.moves.length > 0 && this.moves[0].notation == "..."
609 while (this.cursor >= minCursor) this.undo(null, null, "light");
610 this.lastMove = (minCursor == 1 ? this.moves[0] : null);
611 this.incheck = this.vr.getCheckSquares();
612 this.emitFenIfAnalyze();
614 gotoEnd: function() {
615 if (this.$refs["board"].choices.length > 0) return;
616 this.$refs["board"].resetCurrentAttempt();
617 if (this.cursor == this.moves.length - 1) return;
618 this.gotoMove(this.moves.length - 1);
619 this.emitFenIfAnalyze();
622 if (this.$refs["board"].choices.length > 0) return;
623 this.orientation = V.GetOppCol(this.orientation);
629 <style lang="sass" scoped>
630 [type="checkbox"]#modalEog+div .card
643 display: inline-block
654 background-color: #FACF8C
659 @media screen and (max-width: 767px)
668 // TODO: later, maybe, allow movesList of variable width
669 // or e.g. between 250 and 350px (but more complicated)
675 @media screen and (max-width: 767px)