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"
25 #turnIndicator(v-if="showTurn") {{ turn }}
26 #controls.button-group
27 button(@click="gotoBegin()")
28 img.inline(src="/images/icons/fast-forward_rev.svg")
29 button(@click="undo()")
30 img.inline(src="/images/icons/play_rev.svg")
31 button(v-if="canFlip" @click="flip()")
32 img.inline(src="/images/icons/flip.svg")
34 @click="runAutoplay()"
35 :class="{'in-autoplay': autoplay}"
37 img.inline(src="/images/icons/autoplay.svg")
38 button(@click="play()")
39 img.inline(src="/images/icons/play.svg")
40 button(@click="gotoEnd()")
41 img.inline(src="/images/icons/fast-forward.svg")
45 :canAnalyze="canAnalyze"
46 :canDownload="allowDownloadPGN"
48 :message="game.scoreMsg"
49 :firstNum="firstMoveNumber"
53 @showrules="showRules"
54 @analyze="analyzePosition"
61 import Board from "@/components/Board.vue";
62 import MoveList from "@/components/MoveList.vue";
63 import params from "@/parameters";
64 import { store } from "@/store";
65 import { getSquareId } from "@/utils/squareId";
66 import { getDate } from "@/utils/datetime";
67 import { processModalClick } from "@/utils/modalClick";
68 import { getScoreMessage } from "@/utils/scoring";
69 import { getFullNotation } from "@/utils/notation";
70 import { undoMove } from "@/utils/playUndo";
81 // NOTE: all following variables must be reset at the beginning of a game
82 vr: null, //VariantRules object, game state
85 score: "*", //'*' means 'unfinished'
87 cursor: -1, //index of the move just played
89 firstMoveNumber: 0, //for printing
90 incheck: [], //for Board
100 if (!this.vr) return "";
101 if (this.vr.showMoves != "all") {
103 (this.vr.turn == 'w' ? "White" : "Black") + " to move"];
105 // Cannot flip: racing king or circular chess
107 this.vr.movesCount == 0 && this.game.mycolor == "w"
108 ? this.st.tr["It's your turn!"]
112 // TODO: is it OK to pass "computed" as propoerties?
113 // Also, some are seemingly not recomputed when vr is initialized.
114 showMoves: function() {
115 return this.game.score != "*"
117 : (!!this.vr ? this.vr.showMoves : "none");
119 showTurn: function() {
121 this.game.score == '*' &&
122 !!this.vr && (this.vr.showMoves != "all" || !this.vr.canFlip)
125 canAnalyze: function() {
127 this.game.mode != "analyze" &&
128 !!this.vr && this.vr.canAnalyze
131 canFlip: function() {
132 return !!this.vr && this.vr.canFlip;
134 allowDownloadPGN: function() {
136 this.game.score != "*" ||
137 (!!this.vr && this.vr.showMoves == "all")
141 created: function() {
142 if (!!this.game.fenStart) this.re_setVariables();
144 mounted: function() {
145 if (!("ontouchstart" in window)) {
147 const baseGameDiv = document.getElementById("baseGame");
148 baseGameDiv.tabIndex = 0;
149 baseGameDiv.addEventListener("click", this.focusBg);
150 baseGameDiv.addEventListener("keydown", this.handleKeys);
151 baseGameDiv.addEventListener("wheel", this.handleScroll);
153 document.getElementById("eogDiv")
154 .addEventListener("click", processModalClick);
156 beforeDestroy: function() {
157 if (!!this.autoplayLoop) clearInterval(this.autoplayLoop);
160 focusBg: function() {
161 document.getElementById("baseGame").focus();
163 handleKeys: function(e) {
164 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
183 handleScroll: function(e) {
185 if (e.deltaY < 0) this.undo();
186 else if (e.deltaY > 0) this.play();
188 showRules: function() {
189 //this.$router.push("/variants/" + this.game.vname);
190 window.open("#/variants/" + this.game.vname, "_blank"); //better
192 re_setVariables: function(game) {
193 if (!game) game = this.game; //in case of...
194 this.endgameMessage = "";
195 // "w": default orientation for observed games
196 this.orientation = game.mycolor || "w";
197 this.moves = JSON.parse(JSON.stringify(game.moves || []));
198 // Post-processing: decorate each move with notation and FEN
199 this.vr = new V(game.fenStart);
200 const parsedFen = V.ParseFen(game.fenStart);
201 const firstMoveColor = parsedFen.turn;
202 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2);
203 let L = this.moves.length;
204 this.moves.forEach(move => {
205 // Strategy working also for multi-moves:
206 if (!Array.isArray(move)) move = [move];
207 move.forEach((m,idx) => {
208 m.notation = this.vr.getNotation(m);
209 m.unambiguous = V.GetUnambiguousNotation(m);
211 if (idx < L - 1 && this.vr.getCheckSquares(this.vr.turn).length > 0)
215 if (firstMoveColor == "b") {
216 // 'start' & 'end' is required for Board component
220 start: { x: -1, y: -1 },
221 end: { x: -1, y: -1 },
226 this.positionCursorTo(this.moves.length - 1);
227 this.incheck = this.vr.getCheckSquares(this.vr.turn);
228 const score = this.vr.getCurrentScore();
229 if (L > 0 && this.moves[L - 1].notation != "...") {
230 if (["1-0","0-1"].includes(score))
231 this.moves[L - 1].notation += "#";
232 else if (this.vr.getCheckSquares(this.vr.turn).length > 0)
233 this.moves[L - 1].notation += "+";
236 positionCursorTo: function(index) {
238 // Caution: last move in moves array might be a multi-move
240 if (Array.isArray(this.moves[index])) {
241 const L = this.moves[index].length;
242 this.lastMove = this.moves[index][L - 1];
244 this.lastMove = this.moves[index];
246 } else this.lastMove = null;
248 analyzePosition: function() {
253 this.vr.getFen().replace(/ /g, "_");
254 if (this.game.mycolor)
255 newUrl += "&side=" + this.game.mycolor;
256 // Open in same tab in live games (against cheating)
257 if (this.game.type == "live") this.$router.push(newUrl);
258 else window.open("#" + newUrl);
260 download: function() {
261 const content = this.getPgn();
262 // Prepare and trigger download link
263 let downloadAnchor = document.getElementById("download");
264 downloadAnchor.setAttribute("download", "game.pgn");
265 downloadAnchor.href =
266 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
267 downloadAnchor.click();
271 pgn += '[Site "vchess.club"]\n';
272 pgn += '[Variant "' + this.game.vname + '"]\n';
273 pgn += '[Date "' + getDate(new Date()) + '"]\n';
274 pgn += '[White "' + this.game.players[0].name + '"]\n';
275 pgn += '[Black "' + this.game.players[1].name + '"]\n';
276 pgn += '[Fen "' + this.game.fenStart + '"]\n';
277 pgn += '[Result "' + this.game.score + '"]\n';
279 pgn += '[URL "' + params.serverUrl + '/game/' + this.game.id + '"]\n';
281 for (let i = 0; i < this.moves.length; i += 2) {
282 if (i > 0) pgn += " ";
283 pgn += (i/2+1) + "." + getFullNotation(this.moves[i]);
284 if (i+1 < this.moves.length)
285 pgn += " " + getFullNotation(this.moves[i+1]);
288 for (let i = 0; i < this.moves.length; i += 2) {
289 pgn += getFullNotation(this.moves[i], "unambiguous") + "\n";
290 if (i+1 < this.moves.length)
291 pgn += getFullNotation(this.moves[i+1], "unambiguous") + "\n";
295 showEndgameMsg: function(message) {
296 this.endgameMessage = message;
297 document.getElementById("modalEog").checked = true;
299 runAutoplay: function() {
300 const infinitePlay = () => {
301 if (this.cursor == this.moves.length - 1) {
302 clearInterval(this.autoplayLoop);
303 this.autoplayLoop = null;
304 this.autoplay = false;
307 if (this.inPlay || this.inMultimove)
313 this.autoplay = false;
314 clearInterval(this.autoplayLoop);
315 this.autoplayLoop = null;
317 this.autoplay = true;
319 this.autoplayLoop = setInterval(infinitePlay, 1500);
322 // Animate an elementary move
323 animateMove: function(move, callback) {
324 let startSquare = document.getElementById(getSquareId(move.start));
325 if (!startSquare) return; //shouldn't happen but...
326 let endSquare = document.getElementById(getSquareId(move.end));
327 let rectStart = startSquare.getBoundingClientRect();
328 let rectEnd = endSquare.getBoundingClientRect();
330 x: rectEnd.x - rectStart.x,
331 y: rectEnd.y - rectStart.y
333 let movingPiece = document.querySelector(
334 "#" + getSquareId(move.start) + " > img.piece"
336 // For some unknown reasons Opera get "movingPiece == null" error
337 // TODO: is it calling 'animate()' twice ? One extra time ?
338 if (!movingPiece) return;
339 const squares = document.getElementsByClassName("board");
340 for (let i = 0; i < squares.length; i++) {
341 let square = squares.item(i);
342 if (square.id != getSquareId(move.start))
343 // HACK for animation:
344 // (with positive translate, image slides "under background")
345 square.style.zIndex = "-1";
347 movingPiece.style.transform =
348 "translate(" + translation.x + "px," + translation.y + "px)";
349 movingPiece.style.transitionDuration = "0.25s";
350 movingPiece.style.zIndex = "3000";
352 for (let i = 0; i < squares.length; i++)
353 squares.item(i).style.zIndex = "auto";
354 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
359 emitFenIfAnalyze: function() {
360 if (this.game.mode == "analyze") {
363 !!this.lastMove ? this.lastMove.fen : this.game.fenStart
367 // "light": if gotoMove() or gotoEnd()
368 play: function(move, received, light, noemit) {
369 // Freeze while choices are shown:
370 if (this.$refs["board"].choices.length > 0) return;
373 // Received moves in observed games can arrive too fast:
374 this.stackToPlay.unshift(move);
379 const navigate = !move;
380 const playSubmove = (smove) => {
381 smove.notation = this.vr.getNotation(smove);
382 smove.unambiguous = V.GetUnambiguousNotation(smove);
384 this.lastMove = smove;
385 if (!this.inMultimove) {
386 // Condition is "!navigate" but we mean "!this.autoplay"
388 if (this.cursor < this.moves.length - 1)
389 this.moves = this.moves.slice(0, this.cursor + 1);
390 this.moves.push(smove);
392 this.inMultimove = true; //potentially
394 } else if (!navigate) {
395 // Already in the middle of a multi-move
396 const L = this.moves.length;
397 if (!Array.isArray(this.moves[L-1]))
398 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
400 this.$set(this.moves, L-1, this.moves.concat([smove]));
403 const playMove = () => {
405 ["all", "highlight"].includes(V.ShowMoves) &&
406 (this.autoplay || !!received)
408 if (!Array.isArray(move)) move = [move];
411 const initurn = this.vr.turn;
412 (function executeMove() {
413 const smove = move[moveIdx++];
415 self.animateMove(smove, () => {
417 if (moveIdx < move.length)
418 setTimeout(executeMove, 500);
419 else afterMove(smove, initurn);
423 if (moveIdx < move.length) executeMove();
424 else afterMove(smove, initurn);
428 const computeScore = () => {
429 const score = this.vr.getCurrentScore();
431 if (["1-0","0-1"].includes(score))
432 this.lastMove.notation += "#";
433 else if (this.vr.getCheckSquares(this.vr.turn).length > 0)
434 this.lastMove.notation += "+";
436 if (score != "*" && this.game.mode == "analyze") {
437 const message = getScoreMessage(score);
438 // Just show score on screen (allow undo)
439 this.showEndgameMsg(score + " . " + this.st.tr[message]);
443 const afterMove = (smove, initurn) => {
444 if (this.vr.turn != initurn) {
445 // Turn has changed: move is complete
447 // NOTE: only FEN of last sub-move is required (=> setting it here)
448 smove.fen = this.vr.getFen();
449 // Is opponent in check?
450 this.incheck = this.vr.getCheckSquares(this.vr.turn);
451 this.emitFenIfAnalyze();
452 this.inMultimove = false;
453 this.score = computeScore();
454 if (this.game.mode != "analyze" && !navigate) {
456 // Post-processing (e.g. computer play).
457 const L = this.moves.length;
458 // NOTE: always emit the score, even in unfinished,
459 // to tell Game::processMove() that it's not a received move.
460 this.$emit("newmove", this.moves[L-1], { score: this.score });
463 if (this.stackToPlay.length > 0)
464 // Move(s) arrived in-between
465 this.play(this.stackToPlay.pop(), received, light, noemit);
470 // NOTE: navigate and received are mutually exclusive
472 // The move to navigate to is necessarily full:
473 if (this.cursor == this.moves.length - 1) return; //no more moves
474 move = this.moves[this.cursor + 1];
475 if (!this.autoplay) {
476 // Just play the move:
477 if (!Array.isArray(move)) move = [move];
478 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
480 this.lastMove = move[move.length-1];
481 this.incheck = this.vr.getCheckSquares(this.vr.turn);
482 this.score = computeScore();
483 this.emitFenIfAnalyze();
489 // Forbid playing outside analyze mode, except if move is received.
490 // Sufficient condition because Board already knows which turn it is.
492 this.game.mode != "analyze" &&
495 (this.game.score != "*" || this.cursor < this.moves.length - 1)
499 // To play a received move, cursor must be at the end of the game:
500 if (received && this.cursor < this.moves.length - 1)
504 cancelCurrentMultimove: function() {
505 const L = this.moves.length;
506 let move = this.moves[L-1];
507 if (!Array.isArray(move)) move = [move];
508 for (let i=move.length -1; i >= 0; i--) this.vr.undo(move[i]);
511 this.inMultimove = false;
513 cancelLastMove: function() {
514 // The last played move was canceled (corr game)
518 // "light": if gotoMove() or gotoBegin()
519 undo: function(move, light) {
520 // Freeze while choices are shown:
521 if (this.$refs["board"].choices.length > 0) return;
522 if (this.inMultimove) {
523 this.cancelCurrentMultimove();
524 this.incheck = this.vr.getCheckSquares(this.vr.turn);
528 this.moves.length > 0 && this.moves[0].notation == "..."
531 if (this.cursor < minCursor) return; //no more moves
532 move = this.moves[this.cursor];
534 undoMove(move, this.vr);
535 if (light) this.cursor--;
537 this.positionCursorTo(this.cursor - 1);
538 this.incheck = this.vr.getCheckSquares(this.vr.turn);
539 this.emitFenIfAnalyze();
543 gotoMove: function(index) {
544 if (this.$refs["board"].choices.length > 0) return;
545 if (this.inMultimove) this.cancelCurrentMultimove();
546 if (index == this.cursor) return;
547 if (index < this.cursor) {
548 while (this.cursor > index)
549 this.undo(null, null, "light");
552 // index > this.cursor)
553 while (this.cursor < index)
554 this.play(null, null, "light");
556 // NOTE: next line also re-assign cursor, but it's very light
557 this.positionCursorTo(index);
558 this.incheck = this.vr.getCheckSquares(this.vr.turn);
559 this.emitFenIfAnalyze();
561 gotoBegin: function() {
562 if (this.$refs["board"].choices.length > 0) return;
563 if (this.inMultimove) this.cancelCurrentMultimove();
565 this.moves.length > 0 && this.moves[0].notation == "..."
568 while (this.cursor >= minCursor) this.undo(null, null, "light");
569 this.lastMove = (minCursor == 1 ? this.moves[0] : null);
570 this.incheck = this.vr.getCheckSquares(this.vr.turn);
571 this.emitFenIfAnalyze();
573 gotoEnd: function() {
574 if (this.$refs["board"].choices.length > 0) return;
575 if (this.cursor == this.moves.length - 1) return;
576 this.gotoMove(this.moves.length - 1);
577 this.emitFenIfAnalyze();
580 if (this.$refs["board"].choices.length > 0) return;
581 this.orientation = V.GetOppCol(this.orientation);
587 <style lang="sass" scoped>
588 [type="checkbox"]#modalEog+div .card
601 display: inline-block
612 background-color: #FACF8C
617 @media screen and (max-width: 767px)
626 // TODO: later, maybe, allow movesList of variable width
627 // or e.g. between 250 and 350px (but more complicated)
633 @media screen and (max-width: 767px)