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"
62 import Board from "@/components/Board.vue";
63 import MoveList from "@/components/MoveList.vue";
64 import params from "@/parameters";
65 import { store } from "@/store";
66 import { getSquareId } from "@/utils/squareId";
67 import { getDate } from "@/utils/datetime";
68 import { processModalClick } from "@/utils/modalClick";
69 import { getScoreMessage } from "@/utils/scoring";
70 import { getFullNotation } from "@/utils/notation";
71 import { undoMove } from "@/utils/playUndo";
82 // NOTE: all following variables must be reset at the beginning of a game
83 vr: null, //VariantRules object, game state
86 score: "*", //'*' means 'unfinished'
88 cursor: -1, //index of the move just played
90 firstMoveNumber: 0, //for printing
91 incheck: [], //for Board
101 if (!this.vr) return "";
102 if (this.vr.showMoves != "all") {
104 (this.vr.turn == 'w' ? "White" : "Black") + " to move"];
106 // Cannot flip: racing king or circular chess
108 this.vr.movesCount == 0 && this.game.mycolor == "w"
109 ? this.st.tr["It's your turn!"]
113 // TODO: is it OK to pass "computed" as propoerties?
114 // Also, some are seemingly not recomputed when vr is initialized.
115 showMoves: function() {
116 return this.game.score != "*"
118 : (!!this.vr ? this.vr.showMoves : "none");
120 showTurn: function() {
122 this.game.score == '*' &&
123 !!this.vr && (this.vr.showMoves != "all" || !this.vr.canFlip)
126 canAnalyze: function() {
128 this.game.mode != "analyze" &&
129 !!this.vr && this.vr.canAnalyze
132 canFlip: function() {
133 return !!this.vr && this.vr.canFlip;
135 allowDownloadPGN: function() {
137 this.game.score != "*" ||
138 (!!this.vr && this.vr.showMoves == "all")
142 created: function() {
143 if (!!this.game.fenStart) this.re_setVariables();
145 mounted: function() {
146 if (!("ontouchstart" in window)) {
148 const baseGameDiv = document.getElementById("baseGame");
149 baseGameDiv.tabIndex = 0;
150 baseGameDiv.addEventListener("click", this.focusBg);
151 baseGameDiv.addEventListener("keydown", this.handleKeys);
152 baseGameDiv.addEventListener("wheel", this.handleScroll);
154 document.getElementById("eogDiv")
155 .addEventListener("click", processModalClick);
157 beforeDestroy: function() {
158 if (!!this.autoplayLoop) clearInterval(this.autoplayLoop);
161 focusBg: function() {
162 document.getElementById("baseGame").focus();
164 handleKeys: function(e) {
165 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
184 handleScroll: function(e) {
186 if (e.deltaY < 0) this.undo();
187 else if (e.deltaY > 0) this.play();
189 showRules: function() {
190 //this.$router.push("/variants/" + this.game.vname);
191 window.open("#/variants/" + this.game.vname, "_blank"); //better
193 re_setVariables: function(game) {
194 if (!game) game = this.game; //in case of...
195 this.endgameMessage = "";
196 // "w": default orientation for observed games
197 this.orientation = game.mycolor || "w";
198 this.moves = JSON.parse(JSON.stringify(game.moves || []));
199 // Post-processing: decorate each move with notation and FEN
200 this.vr = new V(game.fenStart);
201 const parsedFen = V.ParseFen(game.fenStart);
202 const firstMoveColor = parsedFen.turn;
203 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2);
204 let L = this.moves.length;
205 this.moves.forEach(move => {
206 // Strategy working also for multi-moves:
207 if (!Array.isArray(move)) move = [move];
208 move.forEach((m,idx) => {
209 m.notation = this.vr.getNotation(m);
210 m.unambiguous = V.GetUnambiguousNotation(m);
212 if (idx < L - 1 && this.vr.getCheckSquares(this.vr.turn).length > 0)
216 if (firstMoveColor == "b") {
217 // 'start' & 'end' is required for Board component
221 start: { x: -1, y: -1 },
222 end: { x: -1, y: -1 },
227 this.positionCursorTo(this.moves.length - 1);
228 this.incheck = this.vr.getCheckSquares(this.vr.turn);
229 const score = this.vr.getCurrentScore();
230 if (L > 0 && this.moves[L - 1].notation != "...") {
231 if (["1-0","0-1"].includes(score))
232 this.moves[L - 1].notation += "#";
233 else if (this.vr.getCheckSquares(this.vr.turn).length > 0)
234 this.moves[L - 1].notation += "+";
237 positionCursorTo: function(index) {
239 // Caution: last move in moves array might be a multi-move
241 if (Array.isArray(this.moves[index])) {
242 const L = this.moves[index].length;
243 this.lastMove = this.moves[index][L - 1];
245 this.lastMove = this.moves[index];
247 } else this.lastMove = null;
249 analyzePosition: function() {
254 this.vr.getFen().replace(/ /g, "_");
255 if (this.game.mycolor)
256 newUrl += "&side=" + this.game.mycolor;
257 // Open in same tab in live games (against cheating)
258 if (this.game.type == "live") this.$router.push(newUrl);
259 else window.open("#" + newUrl);
261 download: function() {
262 const content = this.getPgn();
263 // Prepare and trigger download link
264 let downloadAnchor = document.getElementById("download");
265 downloadAnchor.setAttribute("download", "game.pgn");
266 downloadAnchor.href =
267 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
268 downloadAnchor.click();
272 pgn += '[Site "vchess.club"]\n';
273 pgn += '[Variant "' + this.game.vname + '"]\n';
274 pgn += '[Date "' + getDate(new Date()) + '"]\n';
275 pgn += '[White "' + this.game.players[0].name + '"]\n';
276 pgn += '[Black "' + this.game.players[1].name + '"]\n';
277 pgn += '[Fen "' + this.game.fenStart + '"]\n';
278 pgn += '[Result "' + this.game.score + '"]\n';
280 pgn += '[URL "' + params.serverUrl + '/game/' + this.game.id + '"]\n';
282 for (let i = 0; i < this.moves.length; i += 2) {
283 if (i > 0) pgn += " ";
284 pgn += (i/2+1) + "." + getFullNotation(this.moves[i]);
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 pgn += getFullNotation(this.moves[i], "unambiguous") + "\n";
291 if (i+1 < this.moves.length)
292 pgn += getFullNotation(this.moves[i+1], "unambiguous") + "\n";
296 showEndgameMsg: function(message) {
297 this.endgameMessage = message;
298 document.getElementById("modalEog").checked = true;
300 runAutoplay: function() {
301 const infinitePlay = () => {
302 if (this.cursor == this.moves.length - 1) {
303 clearInterval(this.autoplayLoop);
304 this.autoplayLoop = null;
305 this.autoplay = false;
308 if (this.inPlay || this.inMultimove)
314 this.autoplay = false;
315 clearInterval(this.autoplayLoop);
316 this.autoplayLoop = null;
318 this.autoplay = true;
320 this.autoplayLoop = setInterval(infinitePlay, 1500);
323 // Animate an elementary move
324 animateMove: function(move, callback) {
325 let startSquare = document.getElementById(getSquareId(move.start));
326 if (!startSquare) return; //shouldn't happen but...
327 let endSquare = document.getElementById(getSquareId(move.end));
328 let rectStart = startSquare.getBoundingClientRect();
329 let rectEnd = endSquare.getBoundingClientRect();
331 x: rectEnd.x - rectStart.x,
332 y: rectEnd.y - rectStart.y
334 let movingPiece = document.querySelector(
335 "#" + getSquareId(move.start) + " > img.piece"
337 // For some unknown reasons Opera get "movingPiece == null" error
338 // TODO: is it calling 'animate()' twice ? One extra time ?
339 if (!movingPiece) return;
340 const squares = document.getElementsByClassName("board");
341 for (let i = 0; i < squares.length; i++) {
342 let square = squares.item(i);
343 if (square.id != getSquareId(move.start))
344 // HACK for animation:
345 // (with positive translate, image slides "under background")
346 square.style.zIndex = "-1";
348 movingPiece.style.transform =
349 "translate(" + translation.x + "px," + translation.y + "px)";
350 movingPiece.style.transitionDuration = "0.25s";
351 movingPiece.style.zIndex = "3000";
353 for (let i = 0; i < squares.length; i++)
354 squares.item(i).style.zIndex = "auto";
355 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
360 emitFenIfAnalyze: function() {
361 if (this.game.mode == "analyze") {
364 !!this.lastMove ? this.lastMove.fen : this.game.fenStart
368 clickSquare: function(square) {
369 // Some variants make use of a single click at specific times:
370 const move = this.vr.doClick(square);
371 if (!!move) this.play(move);
373 // "light": if gotoMove() or gotoEnd()
374 play: function(move, received, light, noemit) {
375 // Freeze while choices are shown:
376 if (this.$refs["board"].choices.length > 0) return;
379 // Received moves in observed games can arrive too fast:
380 this.stackToPlay.unshift(move);
385 const navigate = !move;
386 const playSubmove = (smove) => {
387 smove.notation = this.vr.getNotation(smove);
388 smove.unambiguous = V.GetUnambiguousNotation(smove);
390 this.lastMove = smove;
391 if (!this.inMultimove) {
392 // Condition is "!navigate" but we mean "!this.autoplay"
394 if (this.cursor < this.moves.length - 1)
395 this.moves = this.moves.slice(0, this.cursor + 1);
396 this.moves.push(smove);
398 this.inMultimove = true; //potentially
400 } else if (!navigate) {
401 // Already in the middle of a multi-move
402 const L = this.moves.length;
403 if (!Array.isArray(this.moves[L-1]))
404 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
406 this.$set(this.moves, L-1, this.moves.concat([smove]));
409 const playMove = () => {
411 ["all", "highlight"].includes(V.ShowMoves) &&
412 (this.autoplay || !!received)
414 if (!Array.isArray(move)) move = [move];
417 const initurn = this.vr.turn;
418 (function executeMove() {
419 const smove = move[moveIdx++];
421 self.animateMove(smove, () => {
423 if (moveIdx < move.length)
424 setTimeout(executeMove, 500);
425 else afterMove(smove, initurn);
429 if (moveIdx < move.length) executeMove();
430 else afterMove(smove, initurn);
434 const computeScore = () => {
435 const score = this.vr.getCurrentScore();
437 if (["1-0","0-1"].includes(score))
438 this.lastMove.notation += "#";
439 else if (this.vr.getCheckSquares(this.vr.turn).length > 0)
440 this.lastMove.notation += "+";
442 if (score != "*" && this.game.mode == "analyze") {
443 const message = getScoreMessage(score);
444 // Just show score on screen (allow undo)
445 this.showEndgameMsg(score + " . " + this.st.tr[message]);
449 const afterMove = (smove, initurn) => {
450 if (this.vr.turn != initurn) {
451 // Turn has changed: move is complete
453 // NOTE: only FEN of last sub-move is required (=> setting it here)
454 smove.fen = this.vr.getFen();
455 // Is opponent in check?
456 this.incheck = this.vr.getCheckSquares(this.vr.turn);
457 this.emitFenIfAnalyze();
458 this.inMultimove = false;
459 this.score = computeScore();
460 if (this.game.mode != "analyze" && !navigate) {
462 // Post-processing (e.g. computer play).
463 const L = this.moves.length;
464 // NOTE: always emit the score, even in unfinished,
465 // to tell Game::processMove() that it's not a received move.
466 this.$emit("newmove", this.moves[L-1], { score: this.score });
469 if (this.stackToPlay.length > 0)
470 // Move(s) arrived in-between
471 this.play(this.stackToPlay.pop(), received, light, noemit);
476 // NOTE: navigate and received are mutually exclusive
478 // The move to navigate to is necessarily full:
479 if (this.cursor == this.moves.length - 1) return; //no more moves
480 move = this.moves[this.cursor + 1];
481 if (!this.autoplay) {
482 // Just play the move:
483 if (!Array.isArray(move)) move = [move];
484 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
486 this.lastMove = move[move.length-1];
487 this.incheck = this.vr.getCheckSquares(this.vr.turn);
488 this.score = computeScore();
489 this.emitFenIfAnalyze();
495 // Forbid playing outside analyze mode, except if move is received.
496 // Sufficient condition because Board already knows which turn it is.
498 this.game.mode != "analyze" &&
501 (this.game.score != "*" || this.cursor < this.moves.length - 1)
505 // To play a received move, cursor must be at the end of the game:
506 if (received && this.cursor < this.moves.length - 1)
510 cancelCurrentMultimove: function() {
511 const L = this.moves.length;
512 let move = this.moves[L-1];
513 if (!Array.isArray(move)) move = [move];
514 for (let i=move.length -1; i >= 0; i--) this.vr.undo(move[i]);
517 this.inMultimove = false;
519 cancelLastMove: function() {
520 // The last played move was canceled (corr game)
524 // "light": if gotoMove() or gotoBegin()
525 undo: function(move, light) {
526 // Freeze while choices are shown:
527 if (this.$refs["board"].choices.length > 0) return;
528 if (this.inMultimove) {
529 this.cancelCurrentMultimove();
530 this.incheck = this.vr.getCheckSquares(this.vr.turn);
534 this.moves.length > 0 && this.moves[0].notation == "..."
537 if (this.cursor < minCursor) return; //no more moves
538 move = this.moves[this.cursor];
540 undoMove(move, this.vr);
541 if (light) this.cursor--;
543 this.positionCursorTo(this.cursor - 1);
544 this.incheck = this.vr.getCheckSquares(this.vr.turn);
545 this.emitFenIfAnalyze();
549 gotoMove: function(index) {
550 if (this.$refs["board"].choices.length > 0) return;
551 if (this.inMultimove) this.cancelCurrentMultimove();
552 if (index == this.cursor) return;
553 if (index < this.cursor) {
554 while (this.cursor > index)
555 this.undo(null, null, "light");
558 // index > this.cursor)
559 while (this.cursor < index)
560 this.play(null, null, "light");
562 // NOTE: next line also re-assign cursor, but it's very light
563 this.positionCursorTo(index);
564 this.incheck = this.vr.getCheckSquares(this.vr.turn);
565 this.emitFenIfAnalyze();
567 gotoBegin: function() {
568 if (this.$refs["board"].choices.length > 0) return;
569 if (this.inMultimove) this.cancelCurrentMultimove();
571 this.moves.length > 0 && this.moves[0].notation == "..."
574 while (this.cursor >= minCursor) this.undo(null, null, "light");
575 this.lastMove = (minCursor == 1 ? this.moves[0] : null);
576 this.incheck = this.vr.getCheckSquares(this.vr.turn);
577 this.emitFenIfAnalyze();
579 gotoEnd: function() {
580 if (this.$refs["board"].choices.length > 0) return;
581 if (this.cursor == this.moves.length - 1) return;
582 this.gotoMove(this.moves.length - 1);
583 this.emitFenIfAnalyze();
586 if (this.$refs["board"].choices.length > 0) return;
587 this.orientation = V.GetOppCol(this.orientation);
593 <style lang="sass" scoped>
594 [type="checkbox"]#modalEog+div .card
607 display: inline-block
618 background-color: #FACF8C
623 @media screen and (max-width: 767px)
632 // TODO: later, maybe, allow movesList of variable width
633 // or e.g. between 250 and 350px (but more complicated)
639 @media screen and (max-width: 767px)