Some fixes + draft Avalanche
[vchess.git] / client / src / components / BaseGame.vue
CommitLineData
a6088c90 1<template lang="pug">
e71161fb 2div#baseGame
7e355d68 3 input#modalEog.modal(type="checkbox")
6808d7a1
BA
4 div#eogDiv(
5 role="dialog"
6 data-checkbox="modalEog"
7 )
9a3049f3 8 .card.text-center
7e355d68 9 label.modal-close(for="modalEog")
9a3049f3 10 h3.section {{ endgameMessage }}
cf94b843
BA
11 #gameContainer
12 #boardContainer
6808d7a1 13 Board(
a6836242 14 ref="board"
6808d7a1
BA
15 :vr="vr"
16 :last-move="lastMove"
07052665 17 :analyze="mode=='analyze'"
20620465 18 :score="game.score"
6808d7a1
BA
19 :user-color="game.mycolor"
20 :orientation="orientation"
21 :vname="game.vname"
22 :incheck="incheck"
23 @play-move="play"
61656127 24 @click-square="clickSquare"
6808d7a1 25 )
20620465 26 #turnIndicator(v-if="showTurn") {{ turn }}
b1e46b33 27 #controls.button-group
b9a5fe01
BA
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")
54ec15eb
BA
34 button(
35 @click="runAutoplay()"
36 :class="{'in-autoplay': autoplay}"
37 )
38 img.inline(src="/images/icons/autoplay.svg")
b9a5fe01
BA
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")
5fc82c80 43 p#fenAnalyze(v-show="showFen") {{ (!!vr ? vr.getFen() : "") }}
cf94b843 44 #movesList
6808d7a1 45 MoveList(
933fd1f9 46 :show="showMoves"
feaf1bf7
BA
47 :canAnalyze="canAnalyze"
48 :canDownload="allowDownloadPGN"
6808d7a1
BA
49 :score="game.score"
50 :message="game.scoreMsg"
51 :firstNum="firstMoveNumber"
52 :moves="moves"
53 :cursor="cursor"
57078452 54 :vname="game.vname"
feaf1bf7
BA
55 @download="download"
56 @showrules="showRules"
07052665 57 @analyze="toggleAnalyze"
6808d7a1 58 @goto-move="gotoMove"
107dc1bd 59 @redraw-board="redrawBoard"
6808d7a1 60 )
41c80bb6 61 .clearer
a6088c90
BA
62</template>
63
64<script>
65import Board from "@/components/Board.vue";
f21cd6d9 66import MoveList from "@/components/MoveList.vue";
2c5d7b20 67import params from "@/parameters";
a6088c90
BA
68import { store } from "@/store";
69import { getSquareId } from "@/utils/squareId";
d4036efe 70import { getDate } from "@/utils/datetime";
602d6bef 71import { processModalClick } from "@/utils/modalClick";
77c50966 72import { getScoreMessage } from "@/utils/scoring";
e71161fb
BA
73import { getFullNotation } from "@/utils/notation";
74import { undoMove } from "@/utils/playUndo";
a6088c90 75export default {
6808d7a1 76 name: "my-base-game",
a6088c90
BA
77 components: {
78 Board,
6808d7a1 79 MoveList
a6088c90 80 },
e71161fb 81 props: ["game"],
a6088c90
BA
82 data: function() {
83 return {
84 st: store.state,
b7c32f1a 85 // NOTE: all following variables must be reset at the beginning of a game
e71161fb 86 vr: null, //VariantRules object, game state
a6088c90
BA
87 endgameMessage: "",
88 orientation: "w",
07052665 89 mode: "",
e50a8025 90 gameMode: "",
a6088c90 91 score: "*", //'*' means 'unfinished'
b7c32f1a 92 moves: [],
a6088c90
BA
93 cursor: -1, //index of the move just played
94 lastMove: null,
74fcb454 95 touchLastClick: "",
5157ce0b 96 firstMoveNumber: 0, //for printing
e71161fb 97 incheck: [], //for Board
57eb158f 98 inMultimove: false,
54ec15eb 99 autoplay: false,
57eb158f
BA
100 inPlay: false,
101 stackToPlay: []
a6088c90
BA
102 };
103 },
104 computed: {
6b9378a6
BA
105 turn: function() {
106 if (!this.vr) return "";
107 if (this.vr.showMoves != "all") {
108 return this.st.tr[
109 (this.vr.turn == 'w' ? "White" : "Black") + " to move"];
110 }
5246b49d 111 // Cannot flip (racing king or circular chess), or Monochrome
6b9378a6
BA
112 return (
113 this.vr.movesCount == 0 && this.game.mycolor == "w"
114 ? this.st.tr["It's your turn!"]
115 : ""
116 );
117 },
07052665
BA
118 showFen: function() {
119 return (
120 this.mode == "analyze" &&
121 this.$router.currentRoute.path.indexOf("/analyse") === -1
122 );
123 },
1ef65040 124 // TODO: is it OK to pass "computed" as properties?
6b9378a6 125 // Also, some are seemingly not recomputed when vr is initialized.
a6088c90 126 showMoves: function() {
00eef1ca
BA
127 return (
128 !!this.game.score && this.game.score != "*"
129 ? "all"
130 : (!!this.vr ? this.vr.showMoves : "none")
131 );
20620465
BA
132 },
133 showTurn: function() {
71ef1664 134 return (
00eef1ca 135 !!this.game.score && this.game.score == '*' &&
5246b49d
BA
136 !!this.vr &&
137 (
138 this.vr.showMoves != "all" ||
139 !this.vr.canFlip ||
140 this.vr.showFirstTurn
141 )
71ef1664 142 );
a6088c90 143 },
20620465 144 canAnalyze: function() {
6b9378a6 145 return (
3cfd9287 146 (!this.game.mode || this.game.mode != "analyze") &&
6b9378a6
BA
147 !!this.vr && this.vr.canAnalyze
148 );
20620465 149 },
71ef1664 150 canFlip: function() {
6b9378a6 151 return !!this.vr && this.vr.canFlip;
71ef1664 152 },
20620465 153 allowDownloadPGN: function() {
6b9378a6 154 return (
00eef1ca
BA
155 (!!this.game.score && this.game.score != "*") ||
156 (!!this.vr && !this.vr.someHiddenMoves)
6b9378a6 157 );
6808d7a1 158 }
a6088c90 159 },
4b0384fa 160 created: function() {
b1e46b33 161 if (!!this.game.fenStart) this.re_setVariables();
4b0384fa 162 },
cf94b843 163 mounted: function() {
e71161fb
BA
164 if (!("ontouchstart" in window)) {
165 // Desktop browser:
166 const baseGameDiv = document.getElementById("baseGame");
167 baseGameDiv.tabIndex = 0;
168 baseGameDiv.addEventListener("click", this.focusBg);
169 baseGameDiv.addEventListener("keydown", this.handleKeys);
170 baseGameDiv.addEventListener("wheel", this.handleScroll);
171 }
42a92848
BA
172 document.getElementById("eogDiv")
173 .addEventListener("click", processModalClick);
cf94b843 174 },
54ec15eb 175 beforeDestroy: function() {
5b18515f
BA
176 // TODO: probably not required
177 this.autoplay = false;
54ec15eb 178 },
a6088c90 179 methods: {
9ca1e26b 180 focusBg: function() {
9ca1e26b
BA
181 document.getElementById("baseGame").focus();
182 },
183 handleKeys: function(e) {
6808d7a1
BA
184 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
185 switch (e.keyCode) {
9ca1e26b
BA
186 case 37:
187 this.undo();
188 break;
189 case 39:
190 this.play();
191 break;
5701c228 192 case 38:
9ca1e26b
BA
193 this.gotoBegin();
194 break;
195 case 40:
196 this.gotoEnd();
197 break;
198 case 32:
9ca1e26b
BA
199 this.flip();
200 break;
201 }
202 },
dcd68c41 203 handleScroll: function(e) {
e71161fb
BA
204 e.preventDefault();
205 if (e.deltaY < 0) this.undo();
206 else if (e.deltaY > 0) this.play();
dcd68c41 207 },
107dc1bd
BA
208 redrawBoard: function() {
209 this.$refs["board"].re_setDrawings();
49dad261 210 },
0e16cb26 211 showRules: function() {
07052665
BA
212 // The button is here only on Game page:
213 document.getElementById("modalRules").checked = true;
0e16cb26 214 },
b1e46b33
BA
215 re_setVariables: function(game) {
216 if (!game) game = this.game; //in case of...
4b0384fa 217 this.endgameMessage = "";
8477e53d 218 // "w": default orientation for observed games
b1e46b33 219 this.orientation = game.mycolor || "w";
07052665 220 this.mode = game.mode || game.type; //TODO: merge...
b1e46b33 221 this.moves = JSON.parse(JSON.stringify(game.moves || []));
e71161fb 222 // Post-processing: decorate each move with notation and FEN
b1e46b33 223 this.vr = new V(game.fenStart);
cd49e617 224 this.inMultimove = false; //in case of
6c7cbfed
BA
225 if (!!this.$refs["board"])
226 // Also in case of:
227 this.$refs["board"].resetCurrentAttempt();
cd49e617
BA
228 let analyseBtn = document.getElementById("analyzeBtn");
229 if (!!analyseBtn) analyseBtn.classList.remove("active");
b1e46b33 230 const parsedFen = V.ParseFen(game.fenStart);
8477e53d 231 const firstMoveColor = parsedFen.turn;
6e0c0bcb 232 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2) + 1;
f54f4c26 233 let L = this.moves.length;
1b56b736
BA
234 this.moves.forEach((move,idx) => {
235 // Strategy working also for multi-moves:
236 if (!Array.isArray(move)) move = [move];
237 move.forEach(m => {
238 m.notation = this.vr.getNotation(m);
239 m.unambiguous = V.GetUnambiguousNotation(m);
240 this.vr.play(m);
e71161fb 241 });
1b56b736
BA
242 const Lm = move.length;
243 move[Lm - 1].fen = this.vr.getFen();
244 if (idx < L - 1 && this.vr.getCheckSquares().length > 0)
245 move[Lm - 1].notation += "+";
246 });
247 this.incheck = this.vr.getCheckSquares();
248 this.score = this.vr.getCurrentScore();
249 if (L >= 1) {
250 const move =
251 !Array.isArray(this.moves[L - 1])
252 ? [this.moves[L - 1]]
253 : this.moves[L - 1];
254 const Lm = move.length;
255 if (["1-0", "0-1"].includes(this.score)) move[Lm - 1].notation += "#";
256 else if (this.incheck.length > 0) move[Lm - 1].notation += "+";
257 }
258 if (this.score != '*') {
259 // Show score on screen
260 const message = getScoreMessage(this.score);
261 this.showEndgameMsg(this.score + " . " + this.st.tr[message]);
6c7cbfed 262 }
8477e53d 263 if (firstMoveColor == "b") {
311cba76 264 // 'start' & 'end' is required for Board component
6808d7a1 265 this.moves.unshift({
6808d7a1 266 notation: "...",
2c5d7b20 267 unambiguous: "...",
311cba76 268 start: { x: -1, y: -1 },
3a2a7b5f
BA
269 end: { x: -1, y: -1 },
270 fen: game.fenStart
6808d7a1 271 });
f54f4c26 272 L++;
697ee580 273 }
af34341d 274 this.positionCursorTo(L - 1);
4b0384fa 275 },
e71161fb
BA
276 positionCursorTo: function(index) {
277 this.cursor = index;
af34341d
BA
278 // Note: last move in moves array might be a multi-move
279 if (index >= 0) this.lastMove = this.moves[index];
280 else this.lastMove = null;
e71161fb 281 },
07052665 282 toggleAnalyze: function() {
8506fc3b 283 // Freeze while choices are shown (and autoplay has priority)
b967d5ba
BA
284 if (
285 this.inPlay ||
286 this.$refs["board"].choices.length > 0 ||
287 this.autoplay
288 ) {
289 return;
290 }
07052665
BA
291 if (this.mode != "analyze") {
292 // Enter analyze mode:
596e24d0 293 this.gameMode = this.mode; //was not 'analyze'
b967d5ba 294 this.mode = "analyze";
e0f26496 295 if (this.inMultimove) this.cancelCurrentMultimove();
07052665
BA
296 this.gameCursor = this.cursor;
297 this.gameMoves = JSON.parse(JSON.stringify(this.moves));
298 document.getElementById("analyzeBtn").classList.add("active");
299 }
300 else {
301 // Exit analyze mode:
e50a8025 302 this.mode = this.gameMode;
07052665
BA
303 this.cursor = this.gameCursor;
304 this.moves = this.gameMoves;
305 let fen = this.game.fenStart;
306 if (this.cursor >= 0) {
307 let mv = this.moves[this.cursor];
308 if (!Array.isArray(mv)) mv = [mv];
309 fen = mv[mv.length-1].fen;
310 }
311 this.vr = new V(fen);
0e912cb2 312 this.inMultimove = false; //in case of
8506fc3b 313 this.$refs["board"].resetCurrentAttempt(); //also in case of
0f0552a7 314 this.incheck = this.vr.getCheckSquares();
8aa314fa
BA
315 if (this.cursor >= 0) this.lastMove = this.moves[this.cursor];
316 else this.lastMove = null;
07052665
BA
317 document.getElementById("analyzeBtn").classList.remove("active");
318 }
603b8a8b 319 },
a6088c90
BA
320 download: function() {
321 const content = this.getPgn();
322 // Prepare and trigger download link
323 let downloadAnchor = document.getElementById("download");
324 downloadAnchor.setAttribute("download", "game.pgn");
6808d7a1
BA
325 downloadAnchor.href =
326 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
a6088c90
BA
327 downloadAnchor.click();
328 },
329 getPgn: function() {
330 let pgn = "";
331 pgn += '[Site "vchess.club"]\n';
834c202a 332 pgn += '[Variant "' + this.game.vname + '"]\n';
1ef65040
BA
333 const gdt = getDate(new Date(this.game.created || Date.now()));
334 pgn += '[Date "' + gdt + '"]\n';
d4036efe
BA
335 pgn += '[White "' + this.game.players[0].name + '"]\n';
336 pgn += '[Black "' + this.game.players[1].name + '"]\n';
834c202a 337 pgn += '[Fen "' + this.game.fenStart + '"]\n';
2c5d7b20 338 pgn += '[Result "' + this.game.score + '"]\n';
fef153df 339 if (!!this.game.id)
1ef65040 340 pgn += '[Url "' + params.serverUrl + '/game/' + this.game.id + '"]\n';
fef153df
BA
341 if (!!this.game.cadence)
342 pgn += '[Cadence "' + this.game.cadence + '"]\n';
2c5d7b20 343 pgn += '\n';
e71161fb 344 for (let i = 0; i < this.moves.length; i += 2) {
2c5d7b20 345 if (i > 0) pgn += " ";
49dad261
BA
346 // Adjust dots notation for a better display:
347 let fullNotation = getFullNotation(this.moves[i]);
348 if (fullNotation == "...") fullNotation = "..";
6e0c0bcb 349 pgn += (i / 2 + this.firstMoveNumber) + "." + fullNotation;
e71161fb 350 if (i+1 < this.moves.length)
2c5d7b20 351 pgn += " " + getFullNotation(this.moves[i+1]);
a6088c90 352 }
2c5d7b20
BA
353 pgn += "\n\n";
354 for (let i = 0; i < this.moves.length; i += 2) {
6e0c0bcb 355 const moveNumber = i / 2 + this.firstMoveNumber;
1ef65040
BA
356 // Skip "dots move", useless for machine reading:
357 if (this.moves[i].notation != "...") {
358 pgn += moveNumber + ".w " +
359 getFullNotation(this.moves[i], "unambiguous") + "\n";
360 }
49dad261 361 if (i+1 < this.moves.length) {
1ef65040 362 pgn += moveNumber + ".b " +
49dad261
BA
363 getFullNotation(this.moves[i+1], "unambiguous") + "\n";
364 }
2c5d7b20
BA
365 }
366 return pgn;
a6088c90 367 },
b988c726
BA
368 showEndgameMsg: function(message) {
369 this.endgameMessage = message;
aae89b49 370 document.getElementById("modalEog").checked = true;
a6088c90 371 },
54ec15eb 372 runAutoplay: function() {
54ec15eb
BA
373 if (this.autoplay) {
374 this.autoplay = false;
5b18515f
BA
375 if (this.stackToPlay.length > 0)
376 // Move(s) arrived in-between
377 this.play(this.stackToPlay.pop(), "received");
378 }
379 else if (this.cursor < this.moves.length - 1) {
54ec15eb 380 this.autoplay = true;
5fc82c80 381 this.play(null, null, null, "autoplay");
54ec15eb
BA
382 }
383 },
e71161fb 384 // Animate an elementary move
63ca2b89 385 animateMove: function(move, callback) {
a6088c90 386 let startSquare = document.getElementById(getSquareId(move.start));
f9c36b2d 387 if (!startSquare) return; //shouldn't happen but...
a6088c90
BA
388 let endSquare = document.getElementById(getSquareId(move.end));
389 let rectStart = startSquare.getBoundingClientRect();
390 let rectEnd = endSquare.getBoundingClientRect();
6808d7a1
BA
391 let translation = {
392 x: rectEnd.x - rectStart.x,
393 y: rectEnd.y - rectStart.y
394 };
395 let movingPiece = document.querySelector(
396 "#" + getSquareId(move.start) + " > img.piece"
397 );
efdfb4c7 398 // For some unknown reasons Opera get "movingPiece == null" error
2c5d7b20 399 // TODO: is it calling 'animate()' twice ? One extra time ?
efdfb4c7 400 if (!movingPiece) return;
a6088c90 401 const squares = document.getElementsByClassName("board");
6808d7a1 402 for (let i = 0; i < squares.length; i++) {
a6088c90 403 let square = squares.item(i);
2c5d7b20
BA
404 if (square.id != getSquareId(move.start))
405 // HACK for animation:
406 // (with positive translate, image slides "under background")
407 square.style.zIndex = "-1";
a6088c90 408 }
6808d7a1
BA
409 movingPiece.style.transform =
410 "translate(" + translation.x + "px," + translation.y + "px)";
910d631b 411 movingPiece.style.transitionDuration = "0.25s";
a6088c90 412 movingPiece.style.zIndex = "3000";
6808d7a1
BA
413 setTimeout(() => {
414 for (let i = 0; i < squares.length; i++)
a6088c90
BA
415 squares.item(i).style.zIndex = "auto";
416 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
63ca2b89 417 callback();
a6088c90
BA
418 }, 250);
419 },
8055eabd
BA
420 // For Analyse mode:
421 emitFenIfAnalyze: function() {
422 if (this.game.mode == "analyze") {
af34341d
BA
423 let fen = this.game.fenStart;
424 if (!!this.lastMove) {
425 if (Array.isArray(this.lastMove)) {
426 const L = this.lastMove.length;
427 fen = this.lastMove[L-1].fen;
428 }
429 else fen = this.lastMove.fen;
430 }
431 this.$emit("fenchange", fen);
8055eabd
BA
432 }
433 },
61656127
BA
434 clickSquare: function(square) {
435 // Some variants make use of a single click at specific times:
1b56b736
BA
436 const move_s = this.vr.doClick(square);
437 if (!!move_s) {
74fcb454
BA
438 const playMove = () => {
439 if (!Array.isArray(move_s)) this.play(move_s);
440 else this.$refs["board"].choices = move_s;
441 }
442 if ("ontouchstart" in window) {
95bc4bf5
BA
443 const squareId = "sq-" + square[0] + "-" + square[1];
444 const highlight = function(on, sq) {
445 let elt = document.getElementById(sq);
446 if (!!elt) {
447 if (on) elt.classList.add("touch-hover");
448 else elt.classList.remove("touch-hover");
449 }
450 }
74fcb454 451 // Touch screen (smartphone): require confirmation
95bc4bf5
BA
452 const squareStr = square[0] + "_" + square[1]
453 if (this.touchLastClick == squareId) {
454 highlight(false, squareId);
455 playMove();
456 }
457 else {
458 highlight(true, squareId);
459 highlight(false, this.touchLastClick);
460 }
461 this.touchLastClick = squareId;
74fcb454
BA
462 }
463 else playMove();
1b56b736 464 }
61656127 465 },
e71161fb 466 // "light": if gotoMove() or gotoEnd()
5fc82c80 467 play: function(move, received, light, autoplay) {
a6836242 468 // Freeze while choices are shown:
6c7cbfed
BA
469 if (
470 !!this.$refs["board"].selectedPiece ||
471 this.$refs["board"].choices.length > 0
472 ) {
473 return;
474 }
d6289b54 475 const navigate = !move;
5fc82c80
BA
476 // Forbid navigation during autoplay:
477 if (navigate && this.autoplay && !autoplay) return;
d6289b54
BA
478 // Forbid playing outside analyze mode, except if move is received.
479 // Sufficient condition because Board already knows which turn it is.
480 if (
481 this.mode != "analyze" &&
482 !navigate &&
483 !received &&
484 (this.game.score != "*" || this.cursor < this.moves.length - 1)
485 ) {
486 return;
487 }
488 if (!!received) {
5b18515f
BA
489 if (this.autoplay || this.inPlay) {
490 // Received moves while autoplaying are stacked,
491 // and in observed games they could arrive too fast:
57eb158f
BA
492 this.stackToPlay.unshift(move);
493 return;
494 }
5b18515f
BA
495 if (this.mode == "analyze") this.toggleAnalyze();
496 if (this.cursor < this.moves.length - 1)
497 // To play a received move, cursor must be at the end of the game:
498 this.gotoEnd();
e50a8025 499 this.inPlay = true;
57eb158f 500 }
ad030c7d 501 // The board may show some possible moves: (TODO: bad solution)
d6289b54 502 this.$refs["board"].resetCurrentAttempt();
e71161fb 503 const playSubmove = (smove) => {
fbd68f75 504 smove.notation = this.vr.getNotation(smove);
2c5d7b20 505 smove.unambiguous = V.GetUnambiguousNotation(smove);
e71161fb 506 this.vr.play(smove);
07052665 507 if (this.inMultimove && !!this.lastMove) {
af34341d
BA
508 if (!Array.isArray(this.lastMove))
509 this.lastMove = [this.lastMove, smove];
510 else this.lastMove.push(smove);
511 }
fbd68f75 512 if (!this.inMultimove) {
af34341d
BA
513 // First sub-move:
514 this.lastMove = smove;
54ec15eb
BA
515 // Condition is "!navigate" but we mean "!this.autoplay"
516 if (!navigate) {
691d6952 517 if (this.cursor < this.moves.length - 1)
54ec15eb
BA
518 this.moves = this.moves.slice(0, this.cursor + 1);
519 this.moves.push(smove);
520 }
fbd68f75
BA
521 this.inMultimove = true; //potentially
522 this.cursor++;
54ec15eb 523 } else if (!navigate) {
fbd68f75
BA
524 // Already in the middle of a multi-move
525 const L = this.moves.length;
526 if (!Array.isArray(this.moves[L-1]))
527 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
6e47d367 528 else this.moves[L-1].push(smove);
e71161fb
BA
529 }
530 };
531 const playMove = () => {
54ec15eb 532 const animate = (
57d9b2c4 533 ["all", "highlight"].includes(V.ShowMoves) &&
54ec15eb
BA
534 (this.autoplay || !!received)
535 );
e71161fb
BA
536 if (!Array.isArray(move)) move = [move];
537 let moveIdx = 0;
538 let self = this;
539 const initurn = this.vr.turn;
540 (function executeMove() {
541 const smove = move[moveIdx++];
ad1e629e 542 // NOTE: condition "smove.start.x >= 0" required for Dynamo,
596e24d0
BA
543 // because second move may be empty. noHighlight condition
544 // is used at least for Chakart.
545 if (animate && smove.start.x >= 0 && !smove.end.noHighlight) {
e71161fb
BA
546 self.animateMove(smove, () => {
547 playSubmove(smove);
5b18515f 548 if (moveIdx < move.length) setTimeout(executeMove, 500);
e71161fb
BA
549 else afterMove(smove, initurn);
550 });
551 } else {
552 playSubmove(smove);
553 if (moveIdx < move.length) executeMove();
554 else afterMove(smove, initurn);
555 }
556 })();
557 };
fbd68f75
BA
558 const computeScore = () => {
559 const score = this.vr.getCurrentScore();
f54f4c26 560 if (!navigate) {
5b18515f 561 if (["1-0", "0-1"].includes(score)) {
af34341d
BA
562 if (Array.isArray(this.lastMove)) {
563 const L = this.lastMove.length;
564 this.lastMove[L - 1].notation += "#";
565 }
566 else this.lastMove.notation += "#";
567 }
f54f4c26 568 }
ff3a8d16 569 if (score != "*" && ["analyze", "versus"].includes(this.mode)) {
fbd68f75 570 const message = getScoreMessage(score);
ff3a8d16 571 // Show score on screen
fbd68f75
BA
572 this.showEndgameMsg(score + " . " + this.st.tr[message]);
573 }
574 return score;
575 };
e71161fb 576 const afterMove = (smove, initurn) => {
e71161fb
BA
577 if (this.vr.turn != initurn) {
578 // Turn has changed: move is complete
3a2a7b5f 579 if (!smove.fen)
2c5d7b20 580 // NOTE: only FEN of last sub-move is required (=> setting it here)
cc00b83c 581 smove.fen = this.vr.getFen();
3a2a7b5f 582 this.emitFenIfAnalyze();
e71161fb 583 this.inMultimove = false;
1b56b736
BA
584 this.incheck = this.vr.getCheckSquares();
585 if (this.incheck.length > 0) smove.notation += "+";
f54f4c26 586 this.score = computeScore();
5b18515f
BA
587 if (this.autoplay) {
588 if (this.cursor < this.moves.length - 1)
5fc82c80 589 setTimeout(() => this.play(null, null, null, "autoplay"), 1000);
5b18515f
BA
590 else {
591 this.autoplay = false;
592 if (this.stackToPlay.length > 0)
593 // Move(s) arrived in-between
594 this.play(this.stackToPlay.pop(), "received");
595 }
596 }
07052665 597 if (this.mode != "analyze" && !navigate) {
5b18515f 598 if (!received) {
5aa14a21 599 // Post-processing (e.g. computer play).
f54f4c26 600 const L = this.moves.length;
5b18515f 601 // NOTE: always emit the score, even in unfinished
f54f4c26
BA
602 this.$emit("newmove", this.moves[L-1], { score: this.score });
603 } else {
57eb158f
BA
604 this.inPlay = false;
605 if (this.stackToPlay.length > 0)
606 // Move(s) arrived in-between
5b18515f 607 this.play(this.stackToPlay.pop(), "received");
57eb158f 608 }
e71161fb
BA
609 }
610 }
611 };
612 // NOTE: navigate and received are mutually exclusive
613 if (navigate) {
614 // The move to navigate to is necessarily full:
615 if (this.cursor == this.moves.length - 1) return; //no more moves
616 move = this.moves[this.cursor + 1];
54ec15eb
BA
617 if (!this.autoplay) {
618 // Just play the move:
619 if (!Array.isArray(move)) move = [move];
620 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
621 if (!light) {
af34341d
BA
622 this.lastMove = move;
623 this.incheck = this.vr.getCheckSquares();
54ec15eb
BA
624 this.score = computeScore();
625 this.emitFenIfAnalyze();
626 }
627 this.cursor++;
628 return;
8055eabd 629 }
e71161fb 630 }
e71161fb
BA
631 playMove();
632 },
633 cancelCurrentMultimove: function() {
e71161fb
BA
634 const L = this.moves.length;
635 let move = this.moves[L-1];
636 if (!Array.isArray(move)) move = [move];
93ce6119 637 for (let i = move.length - 1; i >= 0; i--) this.vr.undo(move[i]);
e71161fb
BA
638 this.moves.pop();
639 this.cursor--;
640 this.inMultimove = false;
641 },
642 cancelLastMove: function() {
643 // The last played move was canceled (corr game)
644 this.undo();
645 this.moves.pop();
646 },
647 // "light": if gotoMove() or gotoBegin()
648 undo: function(move, light) {
6c7cbfed
BA
649 if (
650 this.autoplay ||
651 !!this.$refs["board"].selectedPiece ||
652 this.$refs["board"].choices.length > 0
653 ) {
654 return;
655 }
93ce6119 656 this.$refs["board"].resetCurrentAttempt();
e71161fb
BA
657 if (this.inMultimove) {
658 this.cancelCurrentMultimove();
af34341d 659 this.incheck = this.vr.getCheckSquares();
c3f02a0e
BA
660 if (this.cursor >= 0) this.lastMove = this.moves[this.cursor];
661 else this.lastMove = null;
e71161fb
BA
662 } else {
663 if (!move) {
3a2a7b5f
BA
664 const minCursor =
665 this.moves.length > 0 && this.moves[0].notation == "..."
666 ? 1
667 : 0;
668 if (this.cursor < minCursor) return; //no more moves
e71161fb
BA
669 move = this.moves[this.cursor];
670 }
93ce6119 671 this.$refs["board"].resetCurrentAttempt();
e71161fb
BA
672 undoMove(move, this.vr);
673 if (light) this.cursor--;
674 else {
675 this.positionCursorTo(this.cursor - 1);
af34341d 676 this.incheck = this.vr.getCheckSquares();
8055eabd 677 this.emitFenIfAnalyze();
63ca2b89 678 }
a6088c90 679 }
a6088c90
BA
680 },
681 gotoMove: function(index) {
6c7cbfed
BA
682 if (
683 this.autoplay ||
684 !!this.$refs["board"].selectedPiece ||
685 this.$refs["board"].choices.length > 0
686 ) {
687 return;
688 }
93ce6119 689 this.$refs["board"].resetCurrentAttempt();
e71161fb
BA
690 if (this.inMultimove) this.cancelCurrentMultimove();
691 if (index == this.cursor) return;
692 if (index < this.cursor) {
693 while (this.cursor > index)
694 this.undo(null, null, "light");
695 }
696 else {
697 // index > this.cursor)
698 while (this.cursor < index)
699 this.play(null, null, "light");
700 }
701 // NOTE: next line also re-assign cursor, but it's very light
702 this.positionCursorTo(index);
af34341d 703 this.incheck = this.vr.getCheckSquares();
8055eabd 704 this.emitFenIfAnalyze();
a6088c90
BA
705 },
706 gotoBegin: function() {
6c7cbfed
BA
707 if (
708 this.autoplay ||
709 !!this.$refs["board"].selectedPiece ||
710 this.$refs["board"].choices.length > 0
711 ) {
712 return;
713 }
93ce6119 714 this.$refs["board"].resetCurrentAttempt();
e71161fb 715 if (this.inMultimove) this.cancelCurrentMultimove();
3a2a7b5f
BA
716 const minCursor =
717 this.moves.length > 0 && this.moves[0].notation == "..."
718 ? 1
719 : 0;
720 while (this.cursor >= minCursor) this.undo(null, null, "light");
721 this.lastMove = (minCursor == 1 ? this.moves[0] : null);
af34341d 722 this.incheck = this.vr.getCheckSquares();
8055eabd 723 this.emitFenIfAnalyze();
a6088c90
BA
724 },
725 gotoEnd: function() {
6808d7a1
BA
726 if (this.cursor == this.moves.length - 1) return;
727 this.gotoMove(this.moves.length - 1);
a6088c90
BA
728 },
729 flip: function() {
a6836242 730 if (this.$refs["board"].choices.length > 0) return;
0e16cb26 731 this.orientation = V.GetOppCol(this.orientation);
6808d7a1
BA
732 }
733 }
a6088c90
BA
734};
735</script>
72ccbd67 736
41c80bb6 737<style lang="sass" scoped>
9a3049f3
BA
738[type="checkbox"]#modalEog+div .card
739 min-height: 45px
a06fc4ba 740 max-width: 350px
910d631b 741
cf94b843
BA
742#baseGame
743 width: 100%
4f518610
BA
744 &:focus
745 outline: none
cf94b843
BA
746
747#gameContainer
72ccbd67
BA
748 margin-left: auto
749 margin-right: auto
cf94b843 750
ed06d9e9
BA
751#downloadDiv
752 display: inline-block
753
72ccbd67 754#controls
28b32b4f 755 user-select: none
72ccbd67 756 button
b1e46b33 757 border: none
72ccbd67 758 margin: 0
feaf1bf7
BA
759 padding-top: 5px
760 padding-bottom: 5px
761
5fc82c80
BA
762p#fenAnalyze
763 margin: 5px
764
54ec15eb
BA
765.in-autoplay
766 background-color: #FACF8C
767
feaf1bf7 768img.inline
54ec15eb 769 height: 22px
feaf1bf7
BA
770 padding-top: 5px
771 @media screen and (max-width: 767px)
772 height: 18px
910d631b 773
0e16cb26
BA
774#turnIndicator
775 text-align: center
29bc61be 776 font-weight: bold
910d631b 777
72ccbd67 778#boardContainer
cf94b843 779 float: left
41c80bb6
BA
780// TODO: later, maybe, allow movesList of variable width
781// or e.g. between 250 and 350px (but more complicated)
910d631b 782
cf94b843
BA
783#movesList
784 width: 280px
785 float: left
910d631b 786
96e9585a
BA
787@media screen and (max-width: 767px)
788 #movesList
789 width: 100%
790 float: none
791 clear: both
72ccbd67 792</style>