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 { store } from "@/store";
64 import { getSquareId } from "@/utils/squareId";
65 import { getDate } from "@/utils/datetime";
66 import { processModalClick } from "@/utils/modalClick";
67 import { getScoreMessage } from "@/utils/scoring";
68 import { getFullNotation } from "@/utils/notation";
69 import { undoMove } from "@/utils/playUndo";
80 // NOTE: all following variables must be reset at the beginning of a game
81 vr: null, //VariantRules object, game state
84 score: "*", //'*' means 'unfinished'
86 cursor: -1, //index of the move just played
88 firstMoveNumber: 0, //for printing
89 incheck: [], //for Board
98 showMoves: function() {
99 return this.game.score != "*"
101 : (this.vr ? this.vr.showMoves : "none");
103 showTurn: function() {
105 this.game.score == '*' &&
107 (this.vr.showMoves != "all" || !this.vr.canFlip)
113 if (this.vr.showMoves != "all")
114 return this.st.tr[(this.vr.turn == 'w' ? "White" : "Black") + " to move"]
115 // Cannot flip: racing king or circular chess
116 return this.vr.movesCount == 0 && this.game.mycolor == "w"
117 ? this.st.tr["It's your turn!"]
120 canAnalyze: function() {
121 return this.game.mode != "analyze" && this.vr && this.vr.canAnalyze;
123 canFlip: function() {
124 return this.vr && this.vr.canFlip;
126 allowDownloadPGN: function() {
127 return this.game.score != "*" || (this.vr && this.vr.showMoves == "all");
130 created: function() {
131 if (!!this.game.fenStart) this.re_setVariables();
133 mounted: function() {
134 if (!("ontouchstart" in window)) {
136 const baseGameDiv = document.getElementById("baseGame");
137 baseGameDiv.tabIndex = 0;
138 baseGameDiv.addEventListener("click", this.focusBg);
139 baseGameDiv.addEventListener("keydown", this.handleKeys);
140 baseGameDiv.addEventListener("wheel", this.handleScroll);
142 document.getElementById("eogDiv")
143 .addEventListener("click", processModalClick);
145 beforeDestroy: function() {
146 if (!!this.autoplayLoop) clearInterval(this.autoplayLoop);
149 focusBg: function() {
150 document.getElementById("baseGame").focus();
152 handleKeys: function(e) {
153 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
172 handleScroll: function(e) {
174 if (e.deltaY < 0) this.undo();
175 else if (e.deltaY > 0) this.play();
177 showRules: function() {
178 //this.$router.push("/variants/" + this.game.vname);
179 window.open("#/variants/" + this.game.vname, "_blank"); //better
181 re_setVariables: function(game) {
182 if (!game) game = this.game; //in case of...
183 this.endgameMessage = "";
184 // "w": default orientation for observed games
185 this.orientation = game.mycolor || "w";
186 this.moves = JSON.parse(JSON.stringify(game.moves || []));
187 // Post-processing: decorate each move with notation and FEN
188 this.vr = new V(game.fenStart);
189 const parsedFen = V.ParseFen(game.fenStart);
190 const firstMoveColor = parsedFen.turn;
191 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2);
192 let L = this.moves.length;
193 this.moves.forEach(move => {
194 // Strategy working also for multi-moves:
195 if (!Array.isArray(move)) move = [move];
196 move.forEach((m,idx) => {
197 m.notation = this.vr.getNotation(m);
199 if (idx < L - 1 && this.vr.getCheckSquares(this.vr.turn).length > 0)
203 if (firstMoveColor == "b") {
204 // 'start' & 'end' is required for Board component
207 start: { x: -1, y: -1 },
208 end: { x: -1, y: -1 },
213 this.positionCursorTo(this.moves.length - 1);
214 this.incheck = this.vr.getCheckSquares(this.vr.turn);
215 const score = this.vr.getCurrentScore();
216 if (L > 0 && this.moves[L - 1].notation != "...") {
217 if (["1-0","0-1"].includes(score))
218 this.moves[L - 1].notation += "#";
219 else if (this.vr.getCheckSquares(this.vr.turn).length > 0)
220 this.moves[L - 1].notation += "+";
223 positionCursorTo: function(index) {
225 // Caution: last move in moves array might be a multi-move
227 if (Array.isArray(this.moves[index])) {
228 const L = this.moves[index].length;
229 this.lastMove = this.moves[index][L - 1];
231 this.lastMove = this.moves[index];
233 } else this.lastMove = null;
235 analyzePosition: function() {
240 this.vr.getFen().replace(/ /g, "_");
241 if (this.game.mycolor)
242 newUrl += "&side=" + this.game.mycolor;
243 // Open in same tab in live games (against cheating)
244 if (this.game.type == "live") this.$router.push(newUrl);
245 else window.open("#" + newUrl);
247 download: function() {
248 const content = this.getPgn();
249 // Prepare and trigger download link
250 let downloadAnchor = document.getElementById("download");
251 downloadAnchor.setAttribute("download", "game.pgn");
252 downloadAnchor.href =
253 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
254 downloadAnchor.click();
258 pgn += '[Site "vchess.club"]\n';
259 pgn += '[Variant "' + this.game.vname + '"]\n';
260 pgn += '[Date "' + getDate(new Date()) + '"]\n';
261 pgn += '[White "' + this.game.players[0].name + '"]\n';
262 pgn += '[Black "' + this.game.players[1].name + '"]\n';
263 pgn += '[Fen "' + this.game.fenStart + '"]\n';
264 pgn += '[Result "' + this.game.score + '"]\n\n';
265 for (let i = 0; i < this.moves.length; i += 2) {
266 pgn += (i/2+1) + "." + getFullNotation(this.moves[i]) + " ";
267 if (i+1 < this.moves.length)
268 pgn += getFullNotation(this.moves[i+1]) + " ";
272 showEndgameMsg: function(message) {
273 this.endgameMessage = message;
274 document.getElementById("modalEog").checked = true;
276 runAutoplay: function() {
277 const infinitePlay = () => {
278 if (this.cursor == this.moves.length - 1) {
279 clearInterval(this.autoplayLoop);
280 this.autoplayLoop = null;
281 this.autoplay = false;
284 if (this.inPlay || this.inMultimove)
290 this.autoplay = false;
291 clearInterval(this.autoplayLoop);
292 this.autoplayLoop = null;
294 this.autoplay = true;
296 this.autoplayLoop = setInterval(infinitePlay, 1500);
299 // Animate an elementary move
300 animateMove: function(move, callback) {
301 let startSquare = document.getElementById(getSquareId(move.start));
302 if (!startSquare) return; //shouldn't happen but...
303 let endSquare = document.getElementById(getSquareId(move.end));
304 let rectStart = startSquare.getBoundingClientRect();
305 let rectEnd = endSquare.getBoundingClientRect();
307 x: rectEnd.x - rectStart.x,
308 y: rectEnd.y - rectStart.y
310 let movingPiece = document.querySelector(
311 "#" + getSquareId(move.start) + " > img.piece"
313 // For some unknown reasons Opera get "movingPiece == null" error
314 // TOOO: is it calling 'animate()' twice ? One extra time ?
315 if (!movingPiece) return;
316 // HACK for animation (with positive translate, image slides "under background")
317 // Possible improvement: just alter squares on the piece's way...
318 const squares = document.getElementsByClassName("board");
319 for (let i = 0; i < squares.length; i++) {
320 let square = squares.item(i);
321 if (square.id != getSquareId(move.start)) square.style.zIndex = "-1";
323 movingPiece.style.transform =
324 "translate(" + translation.x + "px," + translation.y + "px)";
325 movingPiece.style.transitionDuration = "0.25s";
326 movingPiece.style.zIndex = "3000";
328 for (let i = 0; i < squares.length; i++)
329 squares.item(i).style.zIndex = "auto";
330 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
335 emitFenIfAnalyze: function() {
336 if (this.game.mode == "analyze") {
339 !!this.lastMove ? this.lastMove.fen : this.game.fenStart
343 // "light": if gotoMove() or gotoEnd()
344 play: function(move, received, light, noemit) {
345 // Freeze while choices are shown:
346 if (this.$refs["board"].choices.length > 0) return;
349 // Received moves in observed games can arrive too fast:
350 this.stackToPlay.unshift(move);
355 const navigate = !move;
356 const playSubmove = (smove) => {
357 smove.notation = this.vr.getNotation(smove);
359 this.lastMove = smove;
360 if (!this.inMultimove) {
361 // Condition is "!navigate" but we mean "!this.autoplay"
363 if (this.cursor < this.moves.length - 1)
364 this.moves = this.moves.slice(0, this.cursor + 1);
365 this.moves.push(smove);
367 this.inMultimove = true; //potentially
369 } else if (!navigate) {
370 // Already in the middle of a multi-move
371 const L = this.moves.length;
372 if (!Array.isArray(this.moves[L-1]))
373 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
375 this.$set(this.moves, L-1, this.moves.concat([smove]));
378 const playMove = () => {
380 V.ShowMoves == "all" &&
381 (this.autoplay || !!received)
383 if (!Array.isArray(move)) move = [move];
386 const initurn = this.vr.turn;
387 (function executeMove() {
388 const smove = move[moveIdx++];
390 self.animateMove(smove, () => {
392 if (moveIdx < move.length)
393 setTimeout(executeMove, 500);
394 else afterMove(smove, initurn);
398 if (moveIdx < move.length) executeMove();
399 else afterMove(smove, initurn);
403 const computeScore = () => {
404 const score = this.vr.getCurrentScore();
406 if (["1-0","0-1"].includes(score))
407 this.lastMove.notation += "#";
408 else if (this.vr.getCheckSquares(this.vr.turn).length > 0)
409 this.lastMove.notation += "+";
411 if (score != "*" && this.game.mode == "analyze") {
412 const message = getScoreMessage(score);
413 // Just show score on screen (allow undo)
414 this.showEndgameMsg(score + " . " + this.st.tr[message]);
418 const afterMove = (smove, initurn) => {
419 if (this.vr.turn != initurn) {
420 // Turn has changed: move is complete
422 // NOTE: only FEN of last sub-move is required (thus setting it here)
423 smove.fen = this.vr.getFen();
424 // Is opponent in check?
425 this.incheck = this.vr.getCheckSquares(this.vr.turn);
426 this.emitFenIfAnalyze();
427 this.inMultimove = false;
428 this.score = computeScore();
429 if (this.game.mode != "analyze" && !navigate) {
431 // Post-processing (e.g. computer play).
432 const L = this.moves.length;
433 // NOTE: always emit the score, even in unfinished,
434 // to tell Game::processMove() that it's not a received move.
435 this.$emit("newmove", this.moves[L-1], { score: this.score });
438 if (this.stackToPlay.length > 0)
439 // Move(s) arrived in-between
440 this.play(this.stackToPlay.pop(), received, light, noemit);
445 // NOTE: navigate and received are mutually exclusive
447 // The move to navigate to is necessarily full:
448 if (this.cursor == this.moves.length - 1) return; //no more moves
449 move = this.moves[this.cursor + 1];
450 if (!this.autoplay) {
451 // Just play the move:
452 if (!Array.isArray(move)) move = [move];
453 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
455 this.lastMove = move[move.length-1];
456 this.incheck = this.vr.getCheckSquares(this.vr.turn);
457 this.score = computeScore();
458 this.emitFenIfAnalyze();
464 // Forbid playing outside analyze mode, except if move is received.
465 // Sufficient condition because Board already knows which turn it is.
467 this.game.mode != "analyze" &&
469 (this.game.score != "*" || this.cursor < this.moves.length - 1)
473 // To play a received move, cursor must be at the end of the game:
474 if (received && this.cursor < this.moves.length - 1)
478 cancelCurrentMultimove: function() {
479 const L = this.moves.length;
480 let move = this.moves[L-1];
481 if (!Array.isArray(move)) move = [move];
482 for (let i=move.length -1; i >= 0; i--) this.vr.undo(move[i]);
485 this.inMultimove = false;
487 cancelLastMove: function() {
488 // The last played move was canceled (corr game)
492 // "light": if gotoMove() or gotoBegin()
493 undo: function(move, light) {
494 // Freeze while choices are shown:
495 if (this.$refs["board"].choices.length > 0) return;
496 if (this.inMultimove) {
497 this.cancelCurrentMultimove();
498 this.incheck = this.vr.getCheckSquares(this.vr.turn);
502 this.moves.length > 0 && this.moves[0].notation == "..."
505 if (this.cursor < minCursor) return; //no more moves
506 move = this.moves[this.cursor];
508 undoMove(move, this.vr);
509 if (light) this.cursor--;
511 this.positionCursorTo(this.cursor - 1);
512 this.incheck = this.vr.getCheckSquares(this.vr.turn);
513 this.emitFenIfAnalyze();
517 gotoMove: function(index) {
518 if (this.$refs["board"].choices.length > 0) return;
519 if (this.inMultimove) this.cancelCurrentMultimove();
520 if (index == this.cursor) return;
521 if (index < this.cursor) {
522 while (this.cursor > index)
523 this.undo(null, null, "light");
526 // index > this.cursor)
527 while (this.cursor < index)
528 this.play(null, null, "light");
530 // NOTE: next line also re-assign cursor, but it's very light
531 this.positionCursorTo(index);
532 this.incheck = this.vr.getCheckSquares(this.vr.turn);
533 this.emitFenIfAnalyze();
535 gotoBegin: function() {
536 if (this.$refs["board"].choices.length > 0) return;
537 if (this.inMultimove) this.cancelCurrentMultimove();
539 this.moves.length > 0 && this.moves[0].notation == "..."
542 while (this.cursor >= minCursor) this.undo(null, null, "light");
543 this.lastMove = (minCursor == 1 ? this.moves[0] : null);
544 this.incheck = this.vr.getCheckSquares(this.vr.turn);
545 this.emitFenIfAnalyze();
547 gotoEnd: function() {
548 if (this.$refs["board"].choices.length > 0) return;
549 if (this.cursor == this.moves.length - 1) return;
550 this.gotoMove(this.moves.length - 1);
551 this.emitFenIfAnalyze();
554 if (this.$refs["board"].choices.length > 0) return;
555 this.orientation = V.GetOppCol(this.orientation);
561 <style lang="sass" scoped>
562 [type="checkbox"]#modalEog+div .card
575 display: inline-block
586 background-color: #FACF8C
591 @media screen and (max-width: 767px)
600 // TODO: later, maybe, allow movesList of variable width
601 // or e.g. between 250 and 350px (but more complicated)
607 @media screen and (max-width: 767px)