Revert to news button in red, no blinking. Add autoplay option
[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 !received &&
469 (this.game.score != "*" || this.cursor < this.moves.length - 1)
470 ) {
471 return;
472 }
473 // To play a received move, cursor must be at the end of the game:
474 if (received && this.cursor < this.moves.length - 1)
475 this.gotoEnd();
476 playMove();
477 },
478 cancelCurrentMultimove: function() {
479 const L = this.moves.length;
480 let move = this.moves[L-1];
481 if (!Array.isArray(move)) move = [move];
482 for (let i=move.length -1; i >= 0; i--) this.vr.undo(move[i]);
483 this.moves.pop();
484 this.cursor--;
485 this.inMultimove = false;
486 },
487 cancelLastMove: function() {
488 // The last played move was canceled (corr game)
489 this.undo();
490 this.moves.pop();
491 },
492 // "light": if gotoMove() or gotoBegin()
493 undo: function(move, light) {
494 // Freeze while choices are shown:
495 if (this.$refs["board"].choices.length > 0) return;
496 if (this.inMultimove) {
497 this.cancelCurrentMultimove();
498 this.incheck = this.vr.getCheckSquares(this.vr.turn);
499 } else {
500 if (!move) {
501 const minCursor =
502 this.moves.length > 0 && this.moves[0].notation == "..."
503 ? 1
504 : 0;
505 if (this.cursor < minCursor) return; //no more moves
506 move = this.moves[this.cursor];
507 }
508 undoMove(move, this.vr);
509 if (light) this.cursor--;
510 else {
511 this.positionCursorTo(this.cursor - 1);
512 this.incheck = this.vr.getCheckSquares(this.vr.turn);
513 this.emitFenIfAnalyze();
514 }
515 }
516 },
517 gotoMove: function(index) {
518 if (this.$refs["board"].choices.length > 0) return;
519 if (this.inMultimove) this.cancelCurrentMultimove();
520 if (index == this.cursor) return;
521 if (index < this.cursor) {
522 while (this.cursor > index)
523 this.undo(null, null, "light");
524 }
525 else {
526 // index > this.cursor)
527 while (this.cursor < index)
528 this.play(null, null, "light");
529 }
530 // NOTE: next line also re-assign cursor, but it's very light
531 this.positionCursorTo(index);
532 this.incheck = this.vr.getCheckSquares(this.vr.turn);
533 this.emitFenIfAnalyze();
534 },
535 gotoBegin: function() {
536 if (this.$refs["board"].choices.length > 0) return;
537 if (this.inMultimove) this.cancelCurrentMultimove();
538 const minCursor =
539 this.moves.length > 0 && this.moves[0].notation == "..."
540 ? 1
541 : 0;
542 while (this.cursor >= minCursor) this.undo(null, null, "light");
543 this.lastMove = (minCursor == 1 ? this.moves[0] : null);
544 this.incheck = this.vr.getCheckSquares(this.vr.turn);
545 this.emitFenIfAnalyze();
546 },
547 gotoEnd: function() {
548 if (this.$refs["board"].choices.length > 0) return;
549 if (this.cursor == this.moves.length - 1) return;
550 this.gotoMove(this.moves.length - 1);
551 this.emitFenIfAnalyze();
552 },
553 flip: function() {
554 if (this.$refs["board"].choices.length > 0) return;
555 this.orientation = V.GetOppCol(this.orientation);
556 }
557 }
558 };
559 </script>
560
561 <style lang="sass" scoped>
562 [type="checkbox"]#modalEog+div .card
563 min-height: 45px
564
565 #baseGame
566 width: 100%
567 &:focus
568 outline: none
569
570 #gameContainer
571 margin-left: auto
572 margin-right: auto
573
574 #downloadDiv
575 display: inline-block
576
577 #controls
578 user-select: none
579 button
580 border: none
581 margin: 0
582 padding-top: 5px
583 padding-bottom: 5px
584
585 .in-autoplay
586 background-color: #FACF8C
587
588 img.inline
589 height: 22px
590 padding-top: 5px
591 @media screen and (max-width: 767px)
592 height: 18px
593
594 #turnIndicator
595 text-align: center
596 font-weight: bold
597
598 #boardContainer
599 float: left
600 // TODO: later, maybe, allow movesList of variable width
601 // or e.g. between 250 and 350px (but more complicated)
602
603 #movesList
604 width: 280px
605 float: left
606
607 @media screen and (max-width: 767px)
608 #movesList
609 width: 100%
610 float: none
611 clear: both
612 </style>