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