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