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