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