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