Disallow analyse mode for Synchrone variant
[vchess.git] / client / src / components / BaseGame.vue
1 <template lang="pug">
2 div#baseGame
3 input#modalEog.modal(type="checkbox")
4 div#eogDiv(
5 role="dialog"
6 data-checkbox="modalEog"
7 )
8 .card.text-center
9 label.modal-close(for="modalEog")
10 h3.section {{ endgameMessage }}
11 #gameContainer
12 #boardContainer
13 Board(
14 ref="board"
15 :vr="vr"
16 :last-move="lastMove"
17 :analyze="game.mode=='analyze'"
18 :score="game.score"
19 :user-color="game.mycolor"
20 :orientation="orientation"
21 :vname="game.vname"
22 :incheck="incheck"
23 @play-move="play"
24 @click-square="clickSquare"
25 )
26 #turnIndicator(v-if="showTurn") {{ turn }}
27 #controls.button-group
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")
34 button(
35 @click="runAutoplay()"
36 :class="{'in-autoplay': autoplay}"
37 )
38 img.inline(src="/images/icons/autoplay.svg")
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")
43 #movesList
44 MoveList(
45 :show="showMoves"
46 :canAnalyze="canAnalyze"
47 :canDownload="allowDownloadPGN"
48 :score="game.score"
49 :message="game.scoreMsg"
50 :firstNum="firstMoveNumber"
51 :moves="moves"
52 :cursor="cursor"
53 @download="download"
54 @showrules="showRules"
55 @analyze="analyzePosition"
56 @goto-move="gotoMove"
57 @reset-arrows="resetArrows"
58 )
59 .clearer
60 </template>
61
62 <script>
63 import Board from "@/components/Board.vue";
64 import MoveList from "@/components/MoveList.vue";
65 import params from "@/parameters";
66 import { store } from "@/store";
67 import { getSquareId } from "@/utils/squareId";
68 import { getDate } from "@/utils/datetime";
69 import { processModalClick } from "@/utils/modalClick";
70 import { getScoreMessage } from "@/utils/scoring";
71 import { getFullNotation } from "@/utils/notation";
72 import { undoMove } from "@/utils/playUndo";
73 export default {
74 name: "my-base-game",
75 components: {
76 Board,
77 MoveList
78 },
79 props: ["game"],
80 data: function() {
81 return {
82 st: store.state,
83 // NOTE: all following variables must be reset at the beginning of a game
84 vr: null, //VariantRules object, game state
85 endgameMessage: "",
86 orientation: "w",
87 score: "*", //'*' means 'unfinished'
88 moves: [],
89 cursor: -1, //index of the move just played
90 lastMove: null,
91 firstMoveNumber: 0, //for printing
92 incheck: [], //for Board
93 inMultimove: false,
94 autoplay: false,
95 autoplayLoop: null,
96 inPlay: false,
97 stackToPlay: []
98 };
99 },
100 computed: {
101 turn: function() {
102 if (!this.vr) return "";
103 if (this.vr.showMoves != "all") {
104 return this.st.tr[
105 (this.vr.turn == 'w' ? "White" : "Black") + " to move"];
106 }
107 // Cannot flip: racing king or circular chess
108 return (
109 this.vr.movesCount == 0 && this.game.mycolor == "w"
110 ? this.st.tr["It's your turn!"]
111 : ""
112 );
113 },
114 // TODO: is it OK to pass "computed" as properties?
115 // Also, some are seemingly not recomputed when vr is initialized.
116 showMoves: function() {
117 return this.game.score != "*"
118 ? "all"
119 : (!!this.vr ? this.vr.showMoves : "none");
120 },
121 showTurn: function() {
122 return (
123 this.game.score == '*' &&
124 !!this.vr && (this.vr.showMoves != "all" || !this.vr.canFlip)
125 );
126 },
127 canAnalyze: function() {
128 return (
129 this.game.mode != "analyze" &&
130 !!this.vr && this.vr.canAnalyze
131 );
132 },
133 canFlip: function() {
134 return !!this.vr && this.vr.canFlip;
135 },
136 allowDownloadPGN: function() {
137 return (
138 this.game.score != "*" ||
139 (!!this.vr && this.vr.showMoves == "all")
140 );
141 }
142 },
143 created: function() {
144 if (!!this.game.fenStart) this.re_setVariables();
145 },
146 mounted: function() {
147 if (!("ontouchstart" in window)) {
148 // Desktop browser:
149 const baseGameDiv = document.getElementById("baseGame");
150 baseGameDiv.tabIndex = 0;
151 baseGameDiv.addEventListener("click", this.focusBg);
152 baseGameDiv.addEventListener("keydown", this.handleKeys);
153 baseGameDiv.addEventListener("wheel", this.handleScroll);
154 }
155 document.getElementById("eogDiv")
156 .addEventListener("click", processModalClick);
157 },
158 beforeDestroy: function() {
159 if (!!this.autoplayLoop) clearInterval(this.autoplayLoop);
160 },
161 methods: {
162 focusBg: function() {
163 document.getElementById("baseGame").focus();
164 },
165 handleKeys: function(e) {
166 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
167 switch (e.keyCode) {
168 case 37:
169 this.undo();
170 break;
171 case 39:
172 this.play();
173 break;
174 case 38:
175 this.gotoBegin();
176 break;
177 case 40:
178 this.gotoEnd();
179 break;
180 case 32:
181 this.flip();
182 break;
183 }
184 },
185 handleScroll: function(e) {
186 e.preventDefault();
187 if (e.deltaY < 0) this.undo();
188 else if (e.deltaY > 0) this.play();
189 },
190 resetArrows: function() {
191 // TODO: make arrows scale with board, and remove this
192 this.$refs["board"].cancelResetArrows();
193 },
194 showRules: function() {
195 //this.$router.push("/variants/" + this.game.vname);
196 window.open("#/variants/" + this.game.vname, "_blank"); //better
197 },
198 re_setVariables: function(game) {
199 if (!game) game = this.game; //in case of...
200 this.endgameMessage = "";
201 // "w": default orientation for observed games
202 this.orientation = game.mycolor || "w";
203 this.moves = JSON.parse(JSON.stringify(game.moves || []));
204 // Post-processing: decorate each move with notation and FEN
205 this.vr = new V(game.fenStart);
206 const parsedFen = V.ParseFen(game.fenStart);
207 const firstMoveColor = parsedFen.turn;
208 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2);
209 let L = this.moves.length;
210 this.moves.forEach(move => {
211 // Strategy working also for multi-moves:
212 if (!Array.isArray(move)) move = [move];
213 move.forEach((m,idx) => {
214 m.index = this.vr.movesCount;
215 m.notation = this.vr.getNotation(m);
216 m.unambiguous = V.GetUnambiguousNotation(m);
217 this.vr.play(m);
218 if (idx < L - 1 && this.vr.getCheckSquares(this.vr.turn).length > 0)
219 m.notation += "+";
220 });
221 });
222 if (firstMoveColor == "b") {
223 // 'start' & 'end' is required for Board component
224 this.moves.unshift({
225 index: parsedFen.movesCount,
226 notation: "...",
227 unambiguous: "...",
228 start: { x: -1, y: -1 },
229 end: { x: -1, y: -1 },
230 fen: game.fenStart
231 });
232 L++;
233 }
234 this.positionCursorTo(this.moves.length - 1);
235 this.incheck = this.vr.getCheckSquares(this.vr.turn);
236 const score = this.vr.getCurrentScore();
237 if (L > 0 && this.moves[L - 1].notation != "...") {
238 if (["1-0","0-1"].includes(score)) this.moves[L - 1].notation += "#";
239 else if (this.incheck.length > 0) this.moves[L - 1].notation += "+";
240 }
241 },
242 positionCursorTo: function(index) {
243 this.cursor = index;
244 // Caution: last move in moves array might be a multi-move
245 if (index >= 0) {
246 if (Array.isArray(this.moves[index])) {
247 const L = this.moves[index].length;
248 this.lastMove = this.moves[index][L - 1];
249 } else {
250 this.lastMove = this.moves[index];
251 }
252 } else this.lastMove = null;
253 },
254 analyzePosition: function() {
255 let newUrl =
256 "/analyse/" +
257 this.game.vname +
258 "/?fen=" +
259 this.vr.getFen().replace(/ /g, "_");
260 if (!!this.game.mycolor) newUrl += "&side=" + this.game.mycolor;
261 window.open("#" + newUrl);
262 },
263 download: function() {
264 const content = this.getPgn();
265 // Prepare and trigger download link
266 let downloadAnchor = document.getElementById("download");
267 downloadAnchor.setAttribute("download", "game.pgn");
268 downloadAnchor.href =
269 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
270 downloadAnchor.click();
271 },
272 getPgn: function() {
273 let pgn = "";
274 pgn += '[Site "vchess.club"]\n';
275 pgn += '[Variant "' + this.game.vname + '"]\n';
276 const gdt = getDate(new Date(this.game.created || Date.now()));
277 pgn += '[Date "' + gdt + '"]\n';
278 pgn += '[White "' + this.game.players[0].name + '"]\n';
279 pgn += '[Black "' + this.game.players[1].name + '"]\n';
280 pgn += '[Fen "' + this.game.fenStart + '"]\n';
281 pgn += '[Result "' + this.game.score + '"]\n';
282 if (!!this.game.id) {
283 pgn += '[Cadence "' + this.game.cadence + '"]\n';
284 pgn += '[Url "' + params.serverUrl + '/game/' + this.game.id + '"]\n';
285 }
286 pgn += '\n';
287 for (let i = 0; i < this.moves.length; i += 2) {
288 if (i > 0) pgn += " ";
289 // Adjust dots notation for a better display:
290 let fullNotation = getFullNotation(this.moves[i]);
291 if (fullNotation == "...") fullNotation = "..";
292 pgn += (this.moves[i].index / 2 + 1) + "." + fullNotation;
293 if (i+1 < this.moves.length)
294 pgn += " " + getFullNotation(this.moves[i+1]);
295 }
296 pgn += "\n\n";
297 for (let i = 0; i < this.moves.length; i += 2) {
298 const moveNumber = this.moves[i].index / 2 + 1;
299 // Skip "dots move", useless for machine reading:
300 if (this.moves[i].notation != "...") {
301 pgn += moveNumber + ".w " +
302 getFullNotation(this.moves[i], "unambiguous") + "\n";
303 }
304 if (i+1 < this.moves.length) {
305 pgn += moveNumber + ".b " +
306 getFullNotation(this.moves[i+1], "unambiguous") + "\n";
307 }
308 }
309 return pgn;
310 },
311 showEndgameMsg: function(message) {
312 this.endgameMessage = message;
313 document.getElementById("modalEog").checked = true;
314 },
315 runAutoplay: function() {
316 const infinitePlay = () => {
317 if (this.cursor == this.moves.length - 1) {
318 clearInterval(this.autoplayLoop);
319 this.autoplayLoop = null;
320 this.autoplay = false;
321 return;
322 }
323 if (this.inPlay || this.inMultimove)
324 // Wait next tick
325 return;
326 this.play();
327 };
328 if (this.autoplay) {
329 this.autoplay = false;
330 clearInterval(this.autoplayLoop);
331 this.autoplayLoop = null;
332 } else {
333 this.autoplay = true;
334 setTimeout(
335 () => {
336 infinitePlay();
337 this.autoplayLoop = setInterval(infinitePlay, 1500);
338 },
339 // Small delay otherwise the first move is played too fast
340 500
341 );
342 }
343 },
344 // Animate an elementary move
345 animateMove: function(move, callback) {
346 let startSquare = document.getElementById(getSquareId(move.start));
347 if (!startSquare) return; //shouldn't happen but...
348 let endSquare = document.getElementById(getSquareId(move.end));
349 let rectStart = startSquare.getBoundingClientRect();
350 let rectEnd = endSquare.getBoundingClientRect();
351 let translation = {
352 x: rectEnd.x - rectStart.x,
353 y: rectEnd.y - rectStart.y
354 };
355 let movingPiece = document.querySelector(
356 "#" + getSquareId(move.start) + " > img.piece"
357 );
358 // For some unknown reasons Opera get "movingPiece == null" error
359 // TODO: is it calling 'animate()' twice ? One extra time ?
360 if (!movingPiece) return;
361 const squares = document.getElementsByClassName("board");
362 for (let i = 0; i < squares.length; i++) {
363 let square = squares.item(i);
364 if (square.id != getSquareId(move.start))
365 // HACK for animation:
366 // (with positive translate, image slides "under background")
367 square.style.zIndex = "-1";
368 }
369 movingPiece.style.transform =
370 "translate(" + translation.x + "px," + translation.y + "px)";
371 movingPiece.style.transitionDuration = "0.25s";
372 movingPiece.style.zIndex = "3000";
373 setTimeout(() => {
374 for (let i = 0; i < squares.length; i++)
375 squares.item(i).style.zIndex = "auto";
376 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
377 callback();
378 }, 250);
379 },
380 // For Analyse mode:
381 emitFenIfAnalyze: function() {
382 if (this.game.mode == "analyze") {
383 this.$emit(
384 "fenchange",
385 !!this.lastMove ? this.lastMove.fen : this.game.fenStart
386 );
387 }
388 },
389 clickSquare: function(square) {
390 // Some variants make use of a single click at specific times:
391 const move = this.vr.doClick(square);
392 if (!!move) this.play(move);
393 },
394 // "light": if gotoMove() or gotoEnd()
395 play: function(move, received, light, noemit) {
396 // Freeze while choices are shown:
397 if (this.$refs["board"].choices.length > 0) return;
398 if (!!noemit) {
399 if (this.inPlay) {
400 // Received moves in observed games can arrive too fast:
401 this.stackToPlay.unshift(move);
402 return;
403 }
404 this.inPlay = true;
405 }
406 const navigate = !move;
407 const playSubmove = (smove) => {
408 smove.notation = this.vr.getNotation(smove);
409 smove.unambiguous = V.GetUnambiguousNotation(smove);
410 this.vr.play(smove);
411 this.lastMove = smove;
412 if (!this.inMultimove) {
413 // Condition is "!navigate" but we mean "!this.autoplay"
414 if (!navigate) {
415 if (this.cursor < this.moves.length - 1)
416 this.moves = this.moves.slice(0, this.cursor + 1);
417 this.moves.push(smove);
418 }
419 this.inMultimove = true; //potentially
420 this.cursor++;
421 } else if (!navigate) {
422 // Already in the middle of a multi-move
423 const L = this.moves.length;
424 if (!Array.isArray(this.moves[L-1]))
425 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
426 else
427 this.$set(this.moves, L-1, this.moves.concat([smove]));
428 }
429 };
430 const playMove = () => {
431 const animate = (
432 ["all", "highlight"].includes(V.ShowMoves) &&
433 (this.autoplay || !!received)
434 );
435 if (!Array.isArray(move)) move = [move];
436 let moveIdx = 0;
437 let self = this;
438 const initurn = this.vr.turn;
439 (function executeMove() {
440 const smove = move[moveIdx++];
441 if (animate) {
442 self.animateMove(smove, () => {
443 playSubmove(smove);
444 if (moveIdx < move.length)
445 setTimeout(executeMove, 500);
446 else afterMove(smove, initurn);
447 });
448 } else {
449 playSubmove(smove);
450 if (moveIdx < move.length) executeMove();
451 else afterMove(smove, initurn);
452 }
453 })();
454 };
455 const computeScore = () => {
456 const score = this.vr.getCurrentScore();
457 if (!navigate) {
458 if (["1-0","0-1"].includes(score)) this.lastMove.notation += "#";
459 else if (this.incheck.length > 0) this.lastMove.notation += "+";
460 }
461 if (score != "*" && this.game.mode == "analyze") {
462 const message = getScoreMessage(score);
463 // Just show score on screen (allow undo)
464 this.showEndgameMsg(score + " . " + this.st.tr[message]);
465 }
466 return score;
467 };
468 const afterMove = (smove, initurn) => {
469 if (this.vr.turn != initurn) {
470 // Turn has changed: move is complete
471 if (!smove.fen)
472 // NOTE: only FEN of last sub-move is required (=> setting it here)
473 smove.fen = this.vr.getFen();
474 // Is opponent in check?
475 this.incheck = this.vr.getCheckSquares(this.vr.turn);
476 this.emitFenIfAnalyze();
477 this.inMultimove = false;
478 this.score = computeScore();
479 if (this.game.mode != "analyze" && !navigate) {
480 if (!noemit) {
481 // Post-processing (e.g. computer play).
482 const L = this.moves.length;
483 // NOTE: always emit the score, even in unfinished,
484 // to tell Game::processMove() that it's not a received move.
485 this.$emit("newmove", this.moves[L-1], { score: this.score });
486 } else {
487 this.inPlay = false;
488 if (this.stackToPlay.length > 0)
489 // Move(s) arrived in-between
490 this.play(this.stackToPlay.pop(), received, light, noemit);
491 }
492 }
493 }
494 };
495 // NOTE: navigate and received are mutually exclusive
496 if (navigate) {
497 // The move to navigate to is necessarily full:
498 if (this.cursor == this.moves.length - 1) return; //no more moves
499 move = this.moves[this.cursor + 1];
500 if (!this.autoplay) {
501 // Just play the move:
502 if (!Array.isArray(move)) move = [move];
503 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
504 if (!light) {
505 this.lastMove = move[move.length-1];
506 this.incheck = this.vr.getCheckSquares(this.vr.turn);
507 this.score = computeScore();
508 this.emitFenIfAnalyze();
509 }
510 this.cursor++;
511 return;
512 }
513 }
514 // Forbid playing outside analyze mode, except if move is received.
515 // Sufficient condition because Board already knows which turn it is.
516 if (
517 this.game.mode != "analyze" &&
518 !navigate &&
519 !received &&
520 (this.game.score != "*" || this.cursor < this.moves.length - 1)
521 ) {
522 return;
523 }
524 // To play a received move, cursor must be at the end of the game:
525 if (received && this.cursor < this.moves.length - 1)
526 this.gotoEnd();
527 playMove();
528 },
529 cancelCurrentMultimove: function() {
530 const L = this.moves.length;
531 let move = this.moves[L-1];
532 if (!Array.isArray(move)) move = [move];
533 for (let i=move.length -1; i >= 0; i--) this.vr.undo(move[i]);
534 this.moves.pop();
535 this.cursor--;
536 this.inMultimove = false;
537 },
538 cancelLastMove: function() {
539 // The last played move was canceled (corr game)
540 this.undo();
541 this.moves.pop();
542 },
543 // "light": if gotoMove() or gotoBegin()
544 undo: function(move, light) {
545 // Freeze while choices are shown:
546 if (this.$refs["board"].choices.length > 0) return;
547 if (this.inMultimove) {
548 this.cancelCurrentMultimove();
549 this.incheck = this.vr.getCheckSquares(this.vr.turn);
550 } else {
551 if (!move) {
552 const minCursor =
553 this.moves.length > 0 && this.moves[0].notation == "..."
554 ? 1
555 : 0;
556 if (this.cursor < minCursor) return; //no more moves
557 move = this.moves[this.cursor];
558 }
559 undoMove(move, this.vr);
560 if (light) this.cursor--;
561 else {
562 this.positionCursorTo(this.cursor - 1);
563 this.incheck = this.vr.getCheckSquares(this.vr.turn);
564 this.emitFenIfAnalyze();
565 }
566 }
567 },
568 gotoMove: function(index) {
569 if (this.$refs["board"].choices.length > 0) return;
570 if (this.inMultimove) this.cancelCurrentMultimove();
571 if (index == this.cursor) return;
572 if (index < this.cursor) {
573 while (this.cursor > index)
574 this.undo(null, null, "light");
575 }
576 else {
577 // index > this.cursor)
578 while (this.cursor < index)
579 this.play(null, null, "light");
580 }
581 // NOTE: next line also re-assign cursor, but it's very light
582 this.positionCursorTo(index);
583 this.incheck = this.vr.getCheckSquares(this.vr.turn);
584 this.emitFenIfAnalyze();
585 },
586 gotoBegin: function() {
587 if (this.$refs["board"].choices.length > 0) return;
588 if (this.inMultimove) this.cancelCurrentMultimove();
589 const minCursor =
590 this.moves.length > 0 && this.moves[0].notation == "..."
591 ? 1
592 : 0;
593 while (this.cursor >= minCursor) this.undo(null, null, "light");
594 this.lastMove = (minCursor == 1 ? this.moves[0] : null);
595 this.incheck = this.vr.getCheckSquares(this.vr.turn);
596 this.emitFenIfAnalyze();
597 },
598 gotoEnd: function() {
599 if (this.$refs["board"].choices.length > 0) return;
600 if (this.cursor == this.moves.length - 1) return;
601 this.gotoMove(this.moves.length - 1);
602 this.emitFenIfAnalyze();
603 },
604 flip: function() {
605 if (this.$refs["board"].choices.length > 0) return;
606 this.orientation = V.GetOppCol(this.orientation);
607 }
608 }
609 };
610 </script>
611
612 <style lang="sass" scoped>
613 [type="checkbox"]#modalEog+div .card
614 min-height: 45px
615
616 #baseGame
617 width: 100%
618 &:focus
619 outline: none
620
621 #gameContainer
622 margin-left: auto
623 margin-right: auto
624
625 #downloadDiv
626 display: inline-block
627
628 #controls
629 user-select: none
630 button
631 border: none
632 margin: 0
633 padding-top: 5px
634 padding-bottom: 5px
635
636 .in-autoplay
637 background-color: #FACF8C
638
639 img.inline
640 height: 22px
641 padding-top: 5px
642 @media screen and (max-width: 767px)
643 height: 18px
644
645 #turnIndicator
646 text-align: center
647 font-weight: bold
648
649 #boardContainer
650 float: left
651 // TODO: later, maybe, allow movesList of variable width
652 // or e.g. between 250 and 350px (but more complicated)
653
654 #movesList
655 width: 280px
656 float: left
657
658 @media screen and (max-width: 767px)
659 #movesList
660 width: 100%
661 float: none
662 clear: both
663 </style>