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