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
99 if (!this.vr) return "";
100 if (this.vr.showMoves != "all") {
102 (this.vr.turn == 'w' ? "White" : "Black") + " to move"];
104 // Cannot flip: racing king or circular chess
106 this.vr.movesCount == 0 && this.game.mycolor == "w"
107 ? this.st.tr["It's your turn!"]
111 // TODO: is it OK to pass "computed" as propoerties?
112 // Also, some are seemingly not recomputed when vr is initialized.
113 showMoves: function() {
114 return this.game.score != "*"
116 : (!!this.vr ? this.vr.showMoves : "none");
118 showTurn: function() {
120 this.game.score == '*' &&
121 !!this.vr && (this.vr.showMoves != "all" || !this.vr.canFlip)
124 canAnalyze: function() {
126 this.game.mode != "analyze" &&
127 !!this.vr && this.vr.canAnalyze
130 canFlip: function() {
131 return !!this.vr && this.vr.canFlip;
133 allowDownloadPGN: function() {
135 this.game.score != "*" ||
136 (!!this.vr && this.vr.showMoves == "all")
140 created: function() {
141 if (!!this.game.fenStart) this.re_setVariables();
143 mounted: function() {
144 if (!("ontouchstart" in window)) {
146 const baseGameDiv = document.getElementById("baseGame");
147 baseGameDiv.tabIndex = 0;
148 baseGameDiv.addEventListener("click", this.focusBg);
149 baseGameDiv.addEventListener("keydown", this.handleKeys);
150 baseGameDiv.addEventListener("wheel", this.handleScroll);
152 document.getElementById("eogDiv")
153 .addEventListener("click", processModalClick);
155 beforeDestroy: function() {
156 if (!!this.autoplayLoop) clearInterval(this.autoplayLoop);
159 focusBg: function() {
160 document.getElementById("baseGame").focus();
162 handleKeys: function(e) {
163 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
182 handleScroll: function(e) {
184 if (e.deltaY < 0) this.undo();
185 else if (e.deltaY > 0) this.play();
187 showRules: function() {
188 //this.$router.push("/variants/" + this.game.vname);
189 window.open("#/variants/" + this.game.vname, "_blank"); //better
191 re_setVariables: function(game) {
192 if (!game) game = this.game; //in case of...
193 this.endgameMessage = "";
194 // "w": default orientation for observed games
195 this.orientation = game.mycolor || "w";
196 this.moves = JSON.parse(JSON.stringify(game.moves || []));
197 // Post-processing: decorate each move with notation and FEN
198 this.vr = new V(game.fenStart);
199 const parsedFen = V.ParseFen(game.fenStart);
200 const firstMoveColor = parsedFen.turn;
201 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2);
202 let L = this.moves.length;
203 this.moves.forEach(move => {
204 // Strategy working also for multi-moves:
205 if (!Array.isArray(move)) move = [move];
206 move.forEach((m,idx) => {
207 m.notation = this.vr.getNotation(m);
209 if (idx < L - 1 && this.vr.getCheckSquares(this.vr.turn).length > 0)
213 if (firstMoveColor == "b") {
214 // 'start' & 'end' is required for Board component
217 start: { x: -1, y: -1 },
218 end: { x: -1, y: -1 },
223 this.positionCursorTo(this.moves.length - 1);
224 this.incheck = this.vr.getCheckSquares(this.vr.turn);
225 const score = this.vr.getCurrentScore();
226 if (L > 0 && this.moves[L - 1].notation != "...") {
227 if (["1-0","0-1"].includes(score))
228 this.moves[L - 1].notation += "#";
229 else if (this.vr.getCheckSquares(this.vr.turn).length > 0)
230 this.moves[L - 1].notation += "+";
233 positionCursorTo: function(index) {
235 // Caution: last move in moves array might be a multi-move
237 if (Array.isArray(this.moves[index])) {
238 const L = this.moves[index].length;
239 this.lastMove = this.moves[index][L - 1];
241 this.lastMove = this.moves[index];
243 } else this.lastMove = null;
245 analyzePosition: function() {
250 this.vr.getFen().replace(/ /g, "_");
251 if (this.game.mycolor)
252 newUrl += "&side=" + this.game.mycolor;
253 // Open in same tab in live games (against cheating)
254 if (this.game.type == "live") this.$router.push(newUrl);
255 else window.open("#" + newUrl);
257 download: function() {
258 const content = this.getPgn();
259 // Prepare and trigger download link
260 let downloadAnchor = document.getElementById("download");
261 downloadAnchor.setAttribute("download", "game.pgn");
262 downloadAnchor.href =
263 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
264 downloadAnchor.click();
268 pgn += '[Site "vchess.club"]\n';
269 pgn += '[Variant "' + this.game.vname + '"]\n';
270 pgn += '[Date "' + getDate(new Date()) + '"]\n';
271 pgn += '[White "' + this.game.players[0].name + '"]\n';
272 pgn += '[Black "' + this.game.players[1].name + '"]\n';
273 pgn += '[Fen "' + this.game.fenStart + '"]\n';
274 pgn += '[Result "' + this.game.score + '"]\n\n';
275 for (let i = 0; i < this.moves.length; i += 2) {
276 pgn += (i/2+1) + "." + getFullNotation(this.moves[i]) + " ";
277 if (i+1 < this.moves.length)
278 pgn += getFullNotation(this.moves[i+1]) + " ";
282 showEndgameMsg: function(message) {
283 this.endgameMessage = message;
284 document.getElementById("modalEog").checked = true;
286 runAutoplay: function() {
287 const infinitePlay = () => {
288 if (this.cursor == this.moves.length - 1) {
289 clearInterval(this.autoplayLoop);
290 this.autoplayLoop = null;
291 this.autoplay = false;
294 if (this.inPlay || this.inMultimove)
300 this.autoplay = false;
301 clearInterval(this.autoplayLoop);
302 this.autoplayLoop = null;
304 this.autoplay = true;
306 this.autoplayLoop = setInterval(infinitePlay, 1500);
309 // Animate an elementary move
310 animateMove: function(move, callback) {
311 let startSquare = document.getElementById(getSquareId(move.start));
312 if (!startSquare) return; //shouldn't happen but...
313 let endSquare = document.getElementById(getSquareId(move.end));
314 let rectStart = startSquare.getBoundingClientRect();
315 let rectEnd = endSquare.getBoundingClientRect();
317 x: rectEnd.x - rectStart.x,
318 y: rectEnd.y - rectStart.y
320 let movingPiece = document.querySelector(
321 "#" + getSquareId(move.start) + " > img.piece"
323 // For some unknown reasons Opera get "movingPiece == null" error
324 // TOOO: is it calling 'animate()' twice ? One extra time ?
325 if (!movingPiece) return;
326 // HACK for animation (with positive translate, image slides "under background")
327 // Possible improvement: just alter squares on the piece's way...
328 const squares = document.getElementsByClassName("board");
329 for (let i = 0; i < squares.length; i++) {
330 let square = squares.item(i);
331 if (square.id != getSquareId(move.start)) square.style.zIndex = "-1";
333 movingPiece.style.transform =
334 "translate(" + translation.x + "px," + translation.y + "px)";
335 movingPiece.style.transitionDuration = "0.25s";
336 movingPiece.style.zIndex = "3000";
338 for (let i = 0; i < squares.length; i++)
339 squares.item(i).style.zIndex = "auto";
340 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
345 emitFenIfAnalyze: function() {
346 if (this.game.mode == "analyze") {
349 !!this.lastMove ? this.lastMove.fen : this.game.fenStart
353 // "light": if gotoMove() or gotoEnd()
354 play: function(move, received, light, noemit) {
355 // Freeze while choices are shown:
356 if (this.$refs["board"].choices.length > 0) return;
359 // Received moves in observed games can arrive too fast:
360 this.stackToPlay.unshift(move);
365 const navigate = !move;
366 const playSubmove = (smove) => {
367 smove.notation = this.vr.getNotation(smove);
369 this.lastMove = smove;
370 if (!this.inMultimove) {
371 // Condition is "!navigate" but we mean "!this.autoplay"
373 if (this.cursor < this.moves.length - 1)
374 this.moves = this.moves.slice(0, this.cursor + 1);
375 this.moves.push(smove);
377 this.inMultimove = true; //potentially
379 } else if (!navigate) {
380 // Already in the middle of a multi-move
381 const L = this.moves.length;
382 if (!Array.isArray(this.moves[L-1]))
383 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
385 this.$set(this.moves, L-1, this.moves.concat([smove]));
388 const playMove = () => {
390 V.ShowMoves == "all" &&
391 (this.autoplay || !!received)
393 if (!Array.isArray(move)) move = [move];
396 const initurn = this.vr.turn;
397 (function executeMove() {
398 const smove = move[moveIdx++];
400 self.animateMove(smove, () => {
402 if (moveIdx < move.length)
403 setTimeout(executeMove, 500);
404 else afterMove(smove, initurn);
408 if (moveIdx < move.length) executeMove();
409 else afterMove(smove, initurn);
413 const computeScore = () => {
414 const score = this.vr.getCurrentScore();
416 if (["1-0","0-1"].includes(score))
417 this.lastMove.notation += "#";
418 else if (this.vr.getCheckSquares(this.vr.turn).length > 0)
419 this.lastMove.notation += "+";
421 if (score != "*" && this.game.mode == "analyze") {
422 const message = getScoreMessage(score);
423 // Just show score on screen (allow undo)
424 this.showEndgameMsg(score + " . " + this.st.tr[message]);
428 const afterMove = (smove, initurn) => {
429 if (this.vr.turn != initurn) {
430 // Turn has changed: move is complete
432 // NOTE: only FEN of last sub-move is required (thus setting it here)
433 smove.fen = this.vr.getFen();
434 // Is opponent in check?
435 this.incheck = this.vr.getCheckSquares(this.vr.turn);
436 this.emitFenIfAnalyze();
437 this.inMultimove = false;
438 this.score = computeScore();
439 if (this.game.mode != "analyze" && !navigate) {
441 // Post-processing (e.g. computer play).
442 const L = this.moves.length;
443 // NOTE: always emit the score, even in unfinished,
444 // to tell Game::processMove() that it's not a received move.
445 this.$emit("newmove", this.moves[L-1], { score: this.score });
448 if (this.stackToPlay.length > 0)
449 // Move(s) arrived in-between
450 this.play(this.stackToPlay.pop(), received, light, noemit);
455 // NOTE: navigate and received are mutually exclusive
457 // The move to navigate to is necessarily full:
458 if (this.cursor == this.moves.length - 1) return; //no more moves
459 move = this.moves[this.cursor + 1];
460 if (!this.autoplay) {
461 // Just play the move:
462 if (!Array.isArray(move)) move = [move];
463 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
465 this.lastMove = move[move.length-1];
466 this.incheck = this.vr.getCheckSquares(this.vr.turn);
467 this.score = computeScore();
468 this.emitFenIfAnalyze();
474 // Forbid playing outside analyze mode, except if move is received.
475 // Sufficient condition because Board already knows which turn it is.
477 this.game.mode != "analyze" &&
480 (this.game.score != "*" || this.cursor < this.moves.length - 1)
484 // To play a received move, cursor must be at the end of the game:
485 if (received && this.cursor < this.moves.length - 1)
489 cancelCurrentMultimove: function() {
490 const L = this.moves.length;
491 let move = this.moves[L-1];
492 if (!Array.isArray(move)) move = [move];
493 for (let i=move.length -1; i >= 0; i--) this.vr.undo(move[i]);
496 this.inMultimove = false;
498 cancelLastMove: function() {
499 // The last played move was canceled (corr game)
503 // "light": if gotoMove() or gotoBegin()
504 undo: function(move, light) {
505 // Freeze while choices are shown:
506 if (this.$refs["board"].choices.length > 0) return;
507 if (this.inMultimove) {
508 this.cancelCurrentMultimove();
509 this.incheck = this.vr.getCheckSquares(this.vr.turn);
513 this.moves.length > 0 && this.moves[0].notation == "..."
516 if (this.cursor < minCursor) return; //no more moves
517 move = this.moves[this.cursor];
519 undoMove(move, this.vr);
520 if (light) this.cursor--;
522 this.positionCursorTo(this.cursor - 1);
523 this.incheck = this.vr.getCheckSquares(this.vr.turn);
524 this.emitFenIfAnalyze();
528 gotoMove: function(index) {
529 if (this.$refs["board"].choices.length > 0) return;
530 if (this.inMultimove) this.cancelCurrentMultimove();
531 if (index == this.cursor) return;
532 if (index < this.cursor) {
533 while (this.cursor > index)
534 this.undo(null, null, "light");
537 // index > this.cursor)
538 while (this.cursor < index)
539 this.play(null, null, "light");
541 // NOTE: next line also re-assign cursor, but it's very light
542 this.positionCursorTo(index);
543 this.incheck = this.vr.getCheckSquares(this.vr.turn);
544 this.emitFenIfAnalyze();
546 gotoBegin: function() {
547 if (this.$refs["board"].choices.length > 0) return;
548 if (this.inMultimove) this.cancelCurrentMultimove();
550 this.moves.length > 0 && this.moves[0].notation == "..."
553 while (this.cursor >= minCursor) this.undo(null, null, "light");
554 this.lastMove = (minCursor == 1 ? this.moves[0] : null);
555 this.incheck = this.vr.getCheckSquares(this.vr.turn);
556 this.emitFenIfAnalyze();
558 gotoEnd: function() {
559 if (this.$refs["board"].choices.length > 0) return;
560 if (this.cursor == this.moves.length - 1) return;
561 this.gotoMove(this.moves.length - 1);
562 this.emitFenIfAnalyze();
565 if (this.$refs["board"].choices.length > 0) return;
566 this.orientation = V.GetOppCol(this.orientation);
572 <style lang="sass" scoped>
573 [type="checkbox"]#modalEog+div .card
586 display: inline-block
597 background-color: #FACF8C
602 @media screen and (max-width: 767px)
611 // TODO: later, maybe, allow movesList of variable width
612 // or e.g. between 250 and 350px (but more complicated)
618 @media screen and (max-width: 767px)