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