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