7156670cac594edb87424989fc31ddfca8e6b880
[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) + 1;
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.notation = this.vr.getNotation(m);
215 m.unambiguous = V.GetUnambiguousNotation(m);
216 this.vr.play(m);
217 if (idx < L - 1 && this.vr.getCheckSquares(this.vr.turn).length > 0)
218 m.notation += "+";
219 });
220 });
221 if (firstMoveColor == "b") {
222 // 'start' & 'end' is required for Board component
223 this.moves.unshift({
224 notation: "...",
225 unambiguous: "...",
226 start: { x: -1, y: -1 },
227 end: { x: -1, y: -1 },
228 fen: game.fenStart
229 });
230 L++;
231 }
232 this.positionCursorTo(this.moves.length - 1);
233 this.incheck = this.vr.getCheckSquares(this.vr.turn);
234 const score = this.vr.getCurrentScore();
235 if (L > 0 && this.moves[L - 1].notation != "...") {
236 if (["1-0","0-1"].includes(score)) this.moves[L - 1].notation += "#";
237 else if (this.incheck.length > 0) this.moves[L - 1].notation += "+";
238 }
239 },
240 positionCursorTo: function(index) {
241 this.cursor = index;
242 // Caution: last move in moves array might be a multi-move
243 if (index >= 0) {
244 if (Array.isArray(this.moves[index])) {
245 const L = this.moves[index].length;
246 this.lastMove = this.moves[index][L - 1];
247 } else {
248 this.lastMove = this.moves[index];
249 }
250 } else this.lastMove = null;
251 },
252 analyzePosition: function() {
253 let newUrl =
254 "/analyse/" +
255 this.game.vname +
256 "/?fen=" +
257 this.vr.getFen().replace(/ /g, "_");
258 if (!!this.game.mycolor) newUrl += "&side=" + this.game.mycolor;
259 window.open("#" + newUrl);
260 },
261 download: function() {
262 const content = this.getPgn();
263 // Prepare and trigger download link
264 let downloadAnchor = document.getElementById("download");
265 downloadAnchor.setAttribute("download", "game.pgn");
266 downloadAnchor.href =
267 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
268 downloadAnchor.click();
269 },
270 getPgn: function() {
271 let pgn = "";
272 pgn += '[Site "vchess.club"]\n';
273 pgn += '[Variant "' + this.game.vname + '"]\n';
274 const gdt = getDate(new Date(this.game.created || Date.now()));
275 pgn += '[Date "' + gdt + '"]\n';
276 pgn += '[White "' + this.game.players[0].name + '"]\n';
277 pgn += '[Black "' + this.game.players[1].name + '"]\n';
278 pgn += '[Fen "' + this.game.fenStart + '"]\n';
279 pgn += '[Result "' + this.game.score + '"]\n';
280 if (!!this.game.id)
281 pgn += '[Url "' + params.serverUrl + '/game/' + this.game.id + '"]\n';
282 if (!!this.game.cadence)
283 pgn += '[Cadence "' + this.game.cadence + '"]\n';
284 pgn += '\n';
285 for (let i = 0; i < this.moves.length; i += 2) {
286 if (i > 0) pgn += " ";
287 // Adjust dots notation for a better display:
288 let fullNotation = getFullNotation(this.moves[i]);
289 if (fullNotation == "...") fullNotation = "..";
290 pgn += (i / 2 + this.firstMoveNumber) + "." + fullNotation;
291 if (i+1 < this.moves.length)
292 pgn += " " + getFullNotation(this.moves[i+1]);
293 }
294 pgn += "\n\n";
295 for (let i = 0; i < this.moves.length; i += 2) {
296 const moveNumber = i / 2 + this.firstMoveNumber;
297 // Skip "dots move", useless for machine reading:
298 if (this.moves[i].notation != "...") {
299 pgn += moveNumber + ".w " +
300 getFullNotation(this.moves[i], "unambiguous") + "\n";
301 }
302 if (i+1 < this.moves.length) {
303 pgn += moveNumber + ".b " +
304 getFullNotation(this.moves[i+1], "unambiguous") + "\n";
305 }
306 }
307 return pgn;
308 },
309 showEndgameMsg: function(message) {
310 this.endgameMessage = message;
311 document.getElementById("modalEog").checked = true;
312 },
313 runAutoplay: function() {
314 const infinitePlay = () => {
315 if (this.cursor == this.moves.length - 1) {
316 clearInterval(this.autoplayLoop);
317 this.autoplayLoop = null;
318 this.autoplay = false;
319 return;
320 }
321 if (this.inPlay || this.inMultimove)
322 // Wait next tick
323 return;
324 this.play();
325 };
326 if (this.autoplay) {
327 this.autoplay = false;
328 clearInterval(this.autoplayLoop);
329 this.autoplayLoop = null;
330 } else {
331 this.autoplay = true;
332 setTimeout(
333 () => {
334 infinitePlay();
335 this.autoplayLoop = setInterval(infinitePlay, 1500);
336 },
337 // Small delay otherwise the first move is played too fast
338 500
339 );
340 }
341 },
342 // Animate an elementary move
343 animateMove: function(move, callback) {
344 let startSquare = document.getElementById(getSquareId(move.start));
345 if (!startSquare) return; //shouldn't happen but...
346 let endSquare = document.getElementById(getSquareId(move.end));
347 let rectStart = startSquare.getBoundingClientRect();
348 let rectEnd = endSquare.getBoundingClientRect();
349 let translation = {
350 x: rectEnd.x - rectStart.x,
351 y: rectEnd.y - rectStart.y
352 };
353 let movingPiece = document.querySelector(
354 "#" + getSquareId(move.start) + " > img.piece"
355 );
356 // For some unknown reasons Opera get "movingPiece == null" error
357 // TODO: is it calling 'animate()' twice ? One extra time ?
358 if (!movingPiece) return;
359 const squares = document.getElementsByClassName("board");
360 for (let i = 0; i < squares.length; i++) {
361 let square = squares.item(i);
362 if (square.id != getSquareId(move.start))
363 // HACK for animation:
364 // (with positive translate, image slides "under background")
365 square.style.zIndex = "-1";
366 }
367 movingPiece.style.transform =
368 "translate(" + translation.x + "px," + translation.y + "px)";
369 movingPiece.style.transitionDuration = "0.25s";
370 movingPiece.style.zIndex = "3000";
371 setTimeout(() => {
372 for (let i = 0; i < squares.length; i++)
373 squares.item(i).style.zIndex = "auto";
374 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
375 callback();
376 }, 250);
377 },
378 // For Analyse mode:
379 emitFenIfAnalyze: function() {
380 if (this.game.mode == "analyze") {
381 this.$emit(
382 "fenchange",
383 !!this.lastMove ? this.lastMove.fen : this.game.fenStart
384 );
385 }
386 },
387 clickSquare: function(square) {
388 // Some variants make use of a single click at specific times:
389 const move = this.vr.doClick(square);
390 if (!!move) this.play(move);
391 },
392 // "light": if gotoMove() or gotoEnd()
393 play: function(move, received, light, noemit) {
394 // Freeze while choices are shown:
395 if (this.$refs["board"].choices.length > 0) return;
396 // The board may show some the possible moves: (TODO: bad solution)
397 this.$refs["board"].resetCurrentAttempt();
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 // Is opponent (or me) in check?
413 this.incheck = this.vr.getCheckSquares(this.vr.turn);
414 if (!this.inMultimove) {
415 // Condition is "!navigate" but we mean "!this.autoplay"
416 if (!navigate) {
417 if (this.cursor < this.moves.length - 1)
418 this.moves = this.moves.slice(0, this.cursor + 1);
419 this.moves.push(smove);
420 }
421 this.inMultimove = true; //potentially
422 this.cursor++;
423 } else if (!navigate) {
424 // Already in the middle of a multi-move
425 const L = this.moves.length;
426 if (!Array.isArray(this.moves[L-1]))
427 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
428 else this.moves[L-1].push(smove);
429 }
430 };
431 const playMove = () => {
432 const animate = (
433 ["all", "highlight"].includes(V.ShowMoves) &&
434 (this.autoplay || !!received)
435 );
436 if (!Array.isArray(move)) move = [move];
437 let moveIdx = 0;
438 let self = this;
439 const initurn = this.vr.turn;
440 (function executeMove() {
441 const smove = move[moveIdx++];
442 // NOTE: condition "smove.start.x >= 0" required for Dynamo,
443 // because second move may be empty.
444 if (animate && smove.start.x >= 0) {
445 self.animateMove(smove, () => {
446 playSubmove(smove);
447 if (moveIdx < move.length)
448 setTimeout(executeMove, 500);
449 else afterMove(smove, initurn);
450 });
451 } else {
452 playSubmove(smove);
453 if (moveIdx < move.length) executeMove();
454 else afterMove(smove, initurn);
455 }
456 })();
457 };
458 const computeScore = () => {
459 const score = this.vr.getCurrentScore();
460 if (!navigate) {
461 if (["1-0","0-1"].includes(score)) this.lastMove.notation += "#";
462 else if (this.incheck.length > 0) this.lastMove.notation += "+";
463 }
464 if (score != "*" && this.game.mode == "analyze") {
465 const message = getScoreMessage(score);
466 // Just show score on screen (allow undo)
467 this.showEndgameMsg(score + " . " + this.st.tr[message]);
468 }
469 return score;
470 };
471 const afterMove = (smove, initurn) => {
472 if (this.vr.turn != initurn) {
473 // Turn has changed: move is complete
474 if (!smove.fen)
475 // NOTE: only FEN of last sub-move is required (=> setting it here)
476 smove.fen = this.vr.getFen();
477 this.emitFenIfAnalyze();
478 this.inMultimove = false;
479 this.score = computeScore();
480 if (this.game.mode != "analyze" && !navigate) {
481 if (!noemit) {
482 // Post-processing (e.g. computer play).
483 const L = this.moves.length;
484 // NOTE: always emit the score, even in unfinished,
485 // to tell Game::processMove() that it's not a received move.
486 this.$emit("newmove", this.moves[L-1], { score: this.score });
487 } else {
488 this.inPlay = false;
489 if (this.stackToPlay.length > 0)
490 // Move(s) arrived in-between
491 this.play(this.stackToPlay.pop(), received, light, noemit);
492 }
493 }
494 }
495 };
496 // NOTE: navigate and received are mutually exclusive
497 if (navigate) {
498 // The move to navigate to is necessarily full:
499 if (this.cursor == this.moves.length - 1) return; //no more moves
500 move = this.moves[this.cursor + 1];
501 if (!this.autoplay) {
502 // Just play the move:
503 if (!Array.isArray(move)) move = [move];
504 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
505 if (!light) {
506 this.lastMove = move[move.length-1];
507 this.incheck = this.vr.getCheckSquares(this.vr.turn);
508 this.score = computeScore();
509 this.emitFenIfAnalyze();
510 }
511 this.cursor++;
512 return;
513 }
514 }
515 // Forbid playing outside analyze mode, except if move is received.
516 // Sufficient condition because Board already knows which turn it is.
517 if (
518 this.game.mode != "analyze" &&
519 !navigate &&
520 !received &&
521 (this.game.score != "*" || this.cursor < this.moves.length - 1)
522 ) {
523 return;
524 }
525 // To play a received move, cursor must be at the end of the game:
526 if (received && this.cursor < this.moves.length - 1)
527 this.gotoEnd();
528 playMove();
529 },
530 cancelCurrentMultimove: function() {
531 const L = this.moves.length;
532 let move = this.moves[L-1];
533 if (!Array.isArray(move)) move = [move];
534 for (let i = move.length - 1; i >= 0; i--) this.vr.undo(move[i]);
535 this.moves.pop();
536 this.cursor--;
537 this.inMultimove = false;
538 },
539 cancelLastMove: function() {
540 // The last played move was canceled (corr game)
541 this.undo();
542 this.moves.pop();
543 },
544 // "light": if gotoMove() or gotoBegin()
545 undo: function(move, light) {
546 // Freeze while choices are shown:
547 if (this.$refs["board"].choices.length > 0) return;
548 this.$refs["board"].resetCurrentAttempt();
549 if (this.inMultimove) {
550 this.cancelCurrentMultimove();
551 this.incheck = this.vr.getCheckSquares(this.vr.turn);
552 } else {
553 if (!move) {
554 const minCursor =
555 this.moves.length > 0 && this.moves[0].notation == "..."
556 ? 1
557 : 0;
558 if (this.cursor < minCursor) return; //no more moves
559 move = this.moves[this.cursor];
560 }
561 this.$refs["board"].resetCurrentAttempt();
562 undoMove(move, this.vr);
563 if (light) this.cursor--;
564 else {
565 this.positionCursorTo(this.cursor - 1);
566 this.incheck = this.vr.getCheckSquares(this.vr.turn);
567 this.emitFenIfAnalyze();
568 }
569 }
570 },
571 gotoMove: function(index) {
572 if (this.$refs["board"].choices.length > 0) return;
573 this.$refs["board"].resetCurrentAttempt();
574 if (this.inMultimove) this.cancelCurrentMultimove();
575 if (index == this.cursor) return;
576 if (index < this.cursor) {
577 while (this.cursor > index)
578 this.undo(null, null, "light");
579 }
580 else {
581 // index > this.cursor)
582 while (this.cursor < index)
583 this.play(null, null, "light");
584 }
585 // NOTE: next line also re-assign cursor, but it's very light
586 this.positionCursorTo(index);
587 this.incheck = this.vr.getCheckSquares(this.vr.turn);
588 this.emitFenIfAnalyze();
589 },
590 gotoBegin: function() {
591 if (this.$refs["board"].choices.length > 0) return;
592 this.$refs["board"].resetCurrentAttempt();
593 if (this.inMultimove) this.cancelCurrentMultimove();
594 const minCursor =
595 this.moves.length > 0 && this.moves[0].notation == "..."
596 ? 1
597 : 0;
598 while (this.cursor >= minCursor) this.undo(null, null, "light");
599 this.lastMove = (minCursor == 1 ? this.moves[0] : null);
600 this.incheck = this.vr.getCheckSquares(this.vr.turn);
601 this.emitFenIfAnalyze();
602 },
603 gotoEnd: function() {
604 if (this.$refs["board"].choices.length > 0) return;
605 this.$refs["board"].resetCurrentAttempt();
606 if (this.cursor == this.moves.length - 1) return;
607 this.gotoMove(this.moves.length - 1);
608 this.emitFenIfAnalyze();
609 },
610 flip: function() {
611 if (this.$refs["board"].choices.length > 0) return;
612 this.orientation = V.GetOppCol(this.orientation);
613 }
614 }
615 };
616 </script>
617
618 <style lang="sass" scoped>
619 [type="checkbox"]#modalEog+div .card
620 min-height: 45px
621
622 #baseGame
623 width: 100%
624 &:focus
625 outline: none
626
627 #gameContainer
628 margin-left: auto
629 margin-right: auto
630
631 #downloadDiv
632 display: inline-block
633
634 #controls
635 user-select: none
636 button
637 border: none
638 margin: 0
639 padding-top: 5px
640 padding-bottom: 5px
641
642 .in-autoplay
643 background-color: #FACF8C
644
645 img.inline
646 height: 22px
647 padding-top: 5px
648 @media screen and (max-width: 767px)
649 height: 18px
650
651 #turnIndicator
652 text-align: center
653 font-weight: bold
654
655 #boardContainer
656 float: left
657 // TODO: later, maybe, allow movesList of variable width
658 // or e.g. between 250 and 350px (but more complicated)
659
660 #movesList
661 width: 280px
662 float: left
663
664 @media screen and (max-width: 767px)
665 #movesList
666 width: 100%
667 float: none
668 clear: both
669 </style>