Implemented multi-move possibility in a moves list => better support for multi-moves...
[vchess.git] / client / src / components / BaseGame.vue
CommitLineData
a6088c90 1<template lang="pug">
e71161fb 2div#baseGame
7e355d68 3 input#modalEog.modal(type="checkbox")
6808d7a1
BA
4 div#eogDiv(
5 role="dialog"
6 data-checkbox="modalEog"
7 )
9a3049f3 8 .card.text-center
7e355d68 9 label.modal-close(for="modalEog")
9a3049f3 10 h3.section {{ endgameMessage }}
602d6bef 11 input#modalAdjust.modal(type="checkbox")
6808d7a1
BA
12 div#adjuster(
13 role="dialog"
14 data-checkbox="modalAdjust"
15 )
9a3049f3 16 .card.text-center
602d6bef 17 label.modal-close(for="modalAdjust")
9a3049f3 18 label(for="boardSize") {{ st.tr["Board size"] }}
6808d7a1
BA
19 input#boardSize.slider(
20 type="range"
21 min="0"
22 max="100"
23 value="50"
24 @input="adjustBoard()"
25 )
cf94b843
BA
26 #gameContainer
27 #boardContainer
6808d7a1
BA
28 Board(
29 :vr="vr"
30 :last-move="lastMove"
20620465
BA
31 :analyze="game.mode=='analyze'"
32 :score="game.score"
6808d7a1
BA
33 :user-color="game.mycolor"
34 :orientation="orientation"
35 :vname="game.vname"
36 :incheck="incheck"
37 @play-move="play"
38 )
20620465 39 #turnIndicator(v-if="showTurn") {{ turn }}
cf94b843 40 #controls
9ddaf8da
BA
41 button(@click="gotoBegin()") <<
42 button(@click="undo()") <
71ef1664 43 button(v-if="canFlip" @click="flip()") &#8645;
9ddaf8da
BA
44 button(@click="play()") >
45 button(@click="gotoEnd()") >>
bd76b456 46 #belowControls
20620465 47 #downloadDiv(v-if="allowDownloadPGN")
4f518610 48 a#download(href="#")
9ddaf8da 49 button(@click="download()") {{ st.tr["Download"] }} PGN
910d631b 50 button(onClick="window.doClick('modalAdjust')") &#10530;
6808d7a1 51 button(
20620465 52 v-if="canAnalyze"
6808d7a1
BA
53 @click="analyzePosition()"
54 )
677fe285 55 | {{ st.tr["Analyse"] }}
20620465 56 // NOTE: variants pages already have a "Rules" link on top
6808d7a1
BA
57 button(
58 v-if="!$route.path.match('/variants/')"
59 @click="showRules()"
60 )
4f518610 61 | {{ st.tr["Rules"] }}
cf94b843 62 #movesList
6808d7a1 63 MoveList(
933fd1f9
BA
64 v-if="showMoves != 'none'"
65 :show="showMoves"
6808d7a1
BA
66 :score="game.score"
67 :message="game.scoreMsg"
68 :firstNum="firstMoveNumber"
69 :moves="moves"
70 :cursor="cursor"
71 @goto-move="gotoMove"
72 )
41c80bb6 73 .clearer
a6088c90
BA
74</template>
75
76<script>
77import Board from "@/components/Board.vue";
f21cd6d9 78import MoveList from "@/components/MoveList.vue";
a6088c90
BA
79import { store } from "@/store";
80import { getSquareId } from "@/utils/squareId";
d4036efe 81import { getDate } from "@/utils/datetime";
602d6bef 82import { processModalClick } from "@/utils/modalClick";
77c50966 83import { getScoreMessage } from "@/utils/scoring";
e71161fb
BA
84import { getFullNotation } from "@/utils/notation";
85import { undoMove } from "@/utils/playUndo";
a6088c90 86export default {
6808d7a1 87 name: "my-base-game",
a6088c90
BA
88 components: {
89 Board,
6808d7a1 90 MoveList
a6088c90 91 },
e71161fb 92 props: ["game"],
a6088c90
BA
93 data: function() {
94 return {
95 st: store.state,
b7c32f1a 96 // NOTE: all following variables must be reset at the beginning of a game
e71161fb 97 vr: null, //VariantRules object, game state
a6088c90
BA
98 endgameMessage: "",
99 orientation: "w",
100 score: "*", //'*' means 'unfinished'
b7c32f1a 101 moves: [],
e71161fb 102 // TODO: later, use subCursor to navigate intra-multimoves?
a6088c90
BA
103 cursor: -1, //index of the move just played
104 lastMove: null,
5157ce0b 105 firstMoveNumber: 0, //for printing
e71161fb
BA
106 incheck: [], //for Board
107 inMultimove: false
a6088c90
BA
108 };
109 },
37cdcbf3 110 watch: {
834c202a
BA
111 // game initial FEN changes when a new game starts
112 "game.fenStart": function() {
4b0384fa 113 this.re_setVariables();
37cdcbf3
BA
114 },
115 },
a6088c90
BA
116 computed: {
117 showMoves: function() {
933fd1f9
BA
118 return this.game.score != "*"
119 ? "all"
120 : (this.vr ? this.vr.showMoves : "none");
20620465
BA
121 },
122 showTurn: function() {
71ef1664
BA
123 return (
124 this.game.score == '*' &&
125 this.vr &&
126 (this.vr.showMoves != "all" || !this.vr.canFlip)
127 );
a6088c90 128 },
58ae6be5 129 turn: function() {
71ef1664
BA
130 if (!this.vr)
131 return "";
132 if (this.vr.showMoves != "all")
133 return this.st.tr[(this.vr.turn == 'w' ? "White" : "Black") + " to move"]
134 // Cannot flip: racing king or circular chess
135 return this.vr.movesCount == 0 && this.game.mycolor == "w"
136 ? this.st.tr["It's your turn!"]
a13cbc0f 137 : "";
58ae6be5 138 },
20620465 139 canAnalyze: function() {
933fd1f9 140 return this.game.mode != "analyze" && this.vr && this.vr.canAnalyze;
20620465 141 },
71ef1664
BA
142 canFlip: function() {
143 return this.vr && this.vr.canFlip;
144 },
20620465 145 allowDownloadPGN: function() {
933fd1f9 146 return this.game.score != "*" || (this.vr && this.vr.showMoves == "all");
6808d7a1 147 }
a6088c90 148 },
4b0384fa 149 created: function() {
6808d7a1 150 if (this.game.fenStart) this.re_setVariables();
4b0384fa 151 },
cf94b843 152 mounted: function() {
e71161fb
BA
153 if (!("ontouchstart" in window)) {
154 // Desktop browser:
155 const baseGameDiv = document.getElementById("baseGame");
156 baseGameDiv.tabIndex = 0;
157 baseGameDiv.addEventListener("click", this.focusBg);
158 baseGameDiv.addEventListener("keydown", this.handleKeys);
159 baseGameDiv.addEventListener("wheel", this.handleScroll);
160 }
6808d7a1
BA
161 [
162 document.getElementById("eogDiv"),
163 document.getElementById("adjuster")
164 ].forEach(elt => elt.addEventListener("click", processModalClick));
96e9585a
BA
165 // Take full width on small screens:
166 let boardSize = parseInt(localStorage.getItem("boardSize"));
6808d7a1
BA
167 if (!boardSize) {
168 boardSize =
169 window.innerWidth >= 768
170 ? 0.75 * Math.min(window.innerWidth, window.innerHeight)
171 : window.innerWidth;
96e9585a 172 }
6808d7a1 173 const movesWidth = window.innerWidth >= 768 ? 280 : 0;
96e9585a
BA
174 document.getElementById("boardContainer").style.width = boardSize + "px";
175 let gameContainer = document.getElementById("gameContainer");
6808d7a1
BA
176 gameContainer.style.width = boardSize + movesWidth + "px";
177 document.getElementById("boardSize").value =
178 (boardSize * 100) / (window.innerWidth - movesWidth);
602d6bef
BA
179 // timeout to avoid calling too many time the adjust method
180 let timeoutLaunched = false;
6808d7a1
BA
181 window.addEventListener("resize", () => {
182 if (!timeoutLaunched) {
602d6bef 183 timeoutLaunched = true;
6808d7a1 184 setTimeout(() => {
602d6bef
BA
185 this.adjustBoard();
186 timeoutLaunched = false;
187 }, 500);
188 }
189 });
cf94b843 190 },
a6088c90 191 methods: {
9ca1e26b 192 focusBg: function() {
9ca1e26b
BA
193 document.getElementById("baseGame").focus();
194 },
602d6bef
BA
195 adjustBoard: function() {
196 const boardContainer = document.getElementById("boardContainer");
6808d7a1 197 if (!boardContainer) return; //no board on page
602d6bef 198 const k = document.getElementById("boardSize").value;
6808d7a1 199 const movesWidth = window.innerWidth >= 768 ? 280 : 0;
602d6bef
BA
200 const minBoardWidth = 240; //TODO: these 240 and 280 are arbitrary...
201 // Value of 0 is board min size; 100 is window.width [- movesWidth]
6808d7a1
BA
202 const boardSize =
203 minBoardWidth +
204 (k * (window.innerWidth - (movesWidth + minBoardWidth))) / 100;
602d6bef
BA
205 localStorage.setItem("boardSize", boardSize);
206 boardContainer.style.width = boardSize + "px";
207 document.getElementById("gameContainer").style.width =
6808d7a1 208 boardSize + movesWidth + "px";
602d6bef 209 },
9ca1e26b 210 handleKeys: function(e) {
6808d7a1
BA
211 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
212 switch (e.keyCode) {
9ca1e26b
BA
213 case 37:
214 this.undo();
215 break;
216 case 39:
217 this.play();
218 break;
5701c228 219 case 38:
9ca1e26b
BA
220 this.gotoBegin();
221 break;
222 case 40:
223 this.gotoEnd();
224 break;
225 case 32:
9ca1e26b
BA
226 this.flip();
227 break;
228 }
229 },
dcd68c41 230 handleScroll: function(e) {
e71161fb
BA
231 e.preventDefault();
232 if (e.deltaY < 0) this.undo();
233 else if (e.deltaY > 0) this.play();
dcd68c41 234 },
0e16cb26
BA
235 showRules: function() {
236 //this.$router.push("/variants/" + this.game.vname);
237 window.open("#/variants/" + this.game.vname, "_blank"); //better
238 },
4b0384fa
BA
239 re_setVariables: function() {
240 this.endgameMessage = "";
8477e53d
BA
241 // "w": default orientation for observed games
242 this.orientation = this.game.mycolor || "w";
4b0384fa 243 this.moves = JSON.parse(JSON.stringify(this.game.moves || []));
e71161fb
BA
244 // Post-processing: decorate each move with notation and FEN
245 this.vr = new V(this.game.fenStart);
8477e53d
BA
246 const parsedFen = V.ParseFen(this.game.fenStart);
247 const firstMoveColor = parsedFen.turn;
248 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2);
d4036efe 249 this.moves.forEach(move => {
e71161fb
BA
250 // Strategy working also for multi-moves:
251 if (!Array.isArray(move)) move = [move];
252 move.forEach(m => {
253 m.notation = this.vr.getNotation(m);
254 this.vr.play(m);
255 });
d4036efe 256 });
8477e53d 257 if (firstMoveColor == "b") {
697ee580 258 // 'end' is required for Board component to check lastMove for e.p.
6808d7a1 259 this.moves.unshift({
6808d7a1
BA
260 notation: "...",
261 end: { x: -1, y: -1 }
262 });
697ee580 263 }
e71161fb 264 this.positionCursorTo(this.moves.length - 1);
9ef63965 265 this.incheck = this.vr.getCheckSquares(this.vr.turn);
4b0384fa 266 },
e71161fb
BA
267 positionCursorTo: function(index) {
268 this.cursor = index;
269 // Caution: last move in moves array might be a multi-move
270 if (index >= 0) {
271 if (Array.isArray(this.moves[index])) {
272 const L = this.moves[index].length;
273 this.lastMove = this.moves[index][L - 1];
274 } else {
275 this.lastMove = this.moves[index];
276 }
277 }
278 else
279 this.lastMove = null;
280 },
63ca2b89 281 analyzePosition: function() {
6808d7a1
BA
282 const newUrl =
283 "/analyse/" +
284 this.game.vname +
285 "/?fen=" +
286 this.vr.getFen().replace(/ /g, "_");
910d631b 287 // Open in same tab in live games (against cheating)
6808d7a1 288 if (this.game.type == "live") this.$router.push(newUrl);
910d631b 289 else window.open("#" + newUrl);
603b8a8b 290 },
a6088c90
BA
291 download: function() {
292 const content = this.getPgn();
293 // Prepare and trigger download link
294 let downloadAnchor = document.getElementById("download");
295 downloadAnchor.setAttribute("download", "game.pgn");
6808d7a1
BA
296 downloadAnchor.href =
297 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
a6088c90
BA
298 downloadAnchor.click();
299 },
300 getPgn: function() {
301 let pgn = "";
302 pgn += '[Site "vchess.club"]\n';
834c202a 303 pgn += '[Variant "' + this.game.vname + '"]\n';
a6088c90 304 pgn += '[Date "' + getDate(new Date()) + '"]\n';
d4036efe
BA
305 pgn += '[White "' + this.game.players[0].name + '"]\n';
306 pgn += '[Black "' + this.game.players[1].name + '"]\n';
834c202a 307 pgn += '[Fen "' + this.game.fenStart + '"]\n';
430a2038 308 pgn += '[Result "' + this.game.score + '"]\n\n';
e71161fb
BA
309 for (let i = 0; i < this.moves.length; i += 2) {
310 pgn += (i/2+1) + "." + getFullNotation(this.moves[i]) + " ";
311 if (i+1 < this.moves.length)
312 pgn += getFullNotation(this.moves[i+1]) + " ";
a6088c90
BA
313 }
314 return pgn + "\n";
315 },
b988c726
BA
316 showEndgameMsg: function(message) {
317 this.endgameMessage = message;
4494c17c 318 let modalBox = document.getElementById("modalEog");
a6088c90 319 modalBox.checked = true;
6808d7a1
BA
320 setTimeout(() => {
321 modalBox.checked = false;
322 }, 2000);
a6088c90 323 },
e71161fb 324 // Animate an elementary move
63ca2b89 325 animateMove: function(move, callback) {
a6088c90
BA
326 let startSquare = document.getElementById(getSquareId(move.start));
327 let endSquare = document.getElementById(getSquareId(move.end));
328 let rectStart = startSquare.getBoundingClientRect();
329 let rectEnd = endSquare.getBoundingClientRect();
6808d7a1
BA
330 let translation = {
331 x: rectEnd.x - rectStart.x,
332 y: rectEnd.y - rectStart.y
333 };
334 let movingPiece = document.querySelector(
335 "#" + getSquareId(move.start) + " > img.piece"
336 );
a6088c90
BA
337 // HACK for animation (with positive translate, image slides "under background")
338 // Possible improvement: just alter squares on the piece's way...
339 const squares = document.getElementsByClassName("board");
6808d7a1 340 for (let i = 0; i < squares.length; i++) {
a6088c90 341 let square = squares.item(i);
6808d7a1 342 if (square.id != getSquareId(move.start)) square.style.zIndex = "-1";
a6088c90 343 }
6808d7a1
BA
344 movingPiece.style.transform =
345 "translate(" + translation.x + "px," + translation.y + "px)";
910d631b 346 movingPiece.style.transitionDuration = "0.25s";
a6088c90 347 movingPiece.style.zIndex = "3000";
6808d7a1
BA
348 setTimeout(() => {
349 for (let i = 0; i < squares.length; i++)
a6088c90
BA
350 squares.item(i).style.zIndex = "auto";
351 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
63ca2b89 352 callback();
a6088c90
BA
353 }, 250);
354 },
e71161fb
BA
355 // "light": if gotoMove() or gotoEnd()
356 // data: some custom data (addTime) to be re-emitted
357 play: function(move, received, light, data) {
9d54ab89 358 const navigate = !move;
e71161fb
BA
359 const playSubmove = (smove) => {
360 if (!navigate) smove.notation = this.vr.getNotation(smove);
361 this.vr.play(smove);
362 this.lastMove = smove;
363 // Is opponent in check?
364 this.incheck = this.vr.getCheckSquares(this.vr.turn);
365 if (!navigate) {
366 if (!this.inMultimove) {
367 if (this.cursor < this.moves.length - 1)
368 this.moves = this.moves.slice(0, Math.max(this.cursor, 0));
369 this.moves.push(smove);
370 this.inMultimove = true; //potentially
371 this.cursor++;
372 } else {
373 // Already in the middle of a multi-move
374 const L = this.moves.length;
375 if (!Array.isArray(this.moves[L-1]))
376 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
377 else
378 this.$set(this.moves, L-1, this.moves.concat([smove]));
379 }
380 }
381 };
382 const playMove = () => {
383 const animate = V.ShowMoves == "all" && received;
384 if (!Array.isArray(move)) move = [move];
385 let moveIdx = 0;
386 let self = this;
387 const initurn = this.vr.turn;
388 (function executeMove() {
389 const smove = move[moveIdx++];
390 if (animate) {
391 self.animateMove(smove, () => {
392 playSubmove(smove);
393 if (moveIdx < move.length)
394 setTimeout(executeMove, 500);
395 else afterMove(smove, initurn);
396 });
397 } else {
398 playSubmove(smove);
399 if (moveIdx < move.length) executeMove();
400 else afterMove(smove, initurn);
401 }
402 })();
403 };
404 const afterMove = (smove, initurn) => {
405 if (this.st.settings.sound == 2)
406 new Audio("/sounds/move.mp3").play().catch(() => {});
407 if (this.vr.turn != initurn) {
408 // Turn has changed: move is complete
409 this.inMultimove = false;
410 const score = this.vr.getCurrentScore();
411 if (score != "*") {
412 const message = getScoreMessage(score);
413 if (!navigate && this.game.mode != "analyze")
414 this.$emit("gameover", score, message);
415 // Just show score on screen (allow undo)
416 else this.showEndgameMsg(score + " . " + message);
417 }
418 if (!navigate && this.game.mode != "analyze") {
419 const L = this.moves.length;
420 // Post-processing (e.g. computer play)
421 this.$emit("newmove", this.moves[L-1], data);
422 }
423 }
424 };
425 // NOTE: navigate and received are mutually exclusive
426 if (navigate) {
427 // The move to navigate to is necessarily full:
428 if (this.cursor == this.moves.length - 1) return; //no more moves
429 move = this.moves[this.cursor + 1];
430 if (light) {
431 // Just play the move, nothing else:
432 if (!Array.isArray(move)) move = [move];
433 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
434 }
435 else playMove();
436 this.cursor++;
437 return;
438 }
63ca2b89
BA
439 // Forbid playing outside analyze mode, except if move is received.
440 // Sufficient condition because Board already knows which turn it is.
6808d7a1 441 if (
6808d7a1 442 this.game.mode != "analyze" &&
e71161fb 443 !received &&
6808d7a1
BA
444 (this.game.score != "*" || this.cursor < this.moves.length - 1)
445 ) {
a6088c90
BA
446 return;
447 }
e71161fb
BA
448 // To play a received move, cursor must be at the end of the game:
449 if (received && this.cursor < this.moves.length - 1)
450 this.gotoEnd();
451 playMove();
452 },
453 cancelCurrentMultimove: function() {
454 // Cancel current multi-move
455 const L = this.moves.length;
456 let move = this.moves[L-1];
457 if (!Array.isArray(move)) move = [move];
458 for (let i=move.length -1; i >= 0; i--) this.vr.undo(move[i]);
459 this.moves.pop();
460 this.cursor--;
461 this.inMultimove = false;
462 },
463 cancelLastMove: function() {
464 // The last played move was canceled (corr game)
465 this.undo();
466 this.moves.pop();
467 },
468 // "light": if gotoMove() or gotoBegin()
469 undo: function(move, light) {
470 if (this.inMultimove) {
471 this.cancelCurrentMultimove();
63ca2b89 472 this.incheck = this.vr.getCheckSquares(this.vr.turn);
e71161fb
BA
473 } else {
474 if (!move) {
475 if (this.cursor < 0) return; //no more moves
476 move = this.moves[this.cursor];
477 }
478 // Caution; if multi-move, undo all submoves from last to first
479 undoMove(move, this.vr);
480 if (light) this.cursor--;
481 else {
482 this.positionCursorTo(this.cursor - 1);
483 if (this.st.settings.sound == 2)
484 new Audio("/sounds/undo.mp3").play().catch(() => {});
485 this.incheck = this.vr.getCheckSquares(this.vr.turn);
63ca2b89 486 }
a6088c90 487 }
a6088c90
BA
488 },
489 gotoMove: function(index) {
e71161fb
BA
490 if (this.inMultimove) this.cancelCurrentMultimove();
491 if (index == this.cursor) return;
492 if (index < this.cursor) {
493 while (this.cursor > index)
494 this.undo(null, null, "light");
495 }
496 else {
497 // index > this.cursor)
498 while (this.cursor < index)
499 this.play(null, null, "light");
500 }
501 // NOTE: next line also re-assign cursor, but it's very light
502 this.positionCursorTo(index);
8b405c81 503 this.incheck = this.vr.getCheckSquares(this.vr.turn);
a6088c90
BA
504 },
505 gotoBegin: function() {
e71161fb
BA
506 if (this.inMultimove) this.cancelCurrentMultimove();
507 while (this.cursor >= 0)
508 this.undo(null, null, "light");
6808d7a1 509 if (this.moves.length > 0 && this.moves[0].notation == "...") {
5701c228
BA
510 this.cursor = 0;
511 this.lastMove = this.moves[0];
6808d7a1 512 } else {
5701c228
BA
513 this.lastMove = null;
514 }
e71161fb 515 this.incheck = [];
a6088c90
BA
516 },
517 gotoEnd: function() {
6808d7a1
BA
518 if (this.cursor == this.moves.length - 1) return;
519 this.gotoMove(this.moves.length - 1);
a6088c90
BA
520 },
521 flip: function() {
0e16cb26 522 this.orientation = V.GetOppCol(this.orientation);
6808d7a1
BA
523 }
524 }
a6088c90
BA
525};
526</script>
72ccbd67 527
41c80bb6 528<style lang="sass" scoped>
9a3049f3
BA
529[type="checkbox"]#modalEog+div .card
530 min-height: 45px
910d631b 531
9a3049f3
BA
532[type="checkbox"]#modalAdjust+div .card
533 padding: 5px
534
cf94b843
BA
535#baseGame
536 width: 100%
4f518610
BA
537 &:focus
538 outline: none
cf94b843
BA
539
540#gameContainer
72ccbd67
BA
541 margin-left: auto
542 margin-right: auto
cf94b843 543
ed06d9e9
BA
544#downloadDiv
545 display: inline-block
546
72ccbd67 547#controls
bd76b456 548 margin: 0 auto
71ef1664 549 text-align: center
72ccbd67
BA
550 button
551 display: inline-block
552 width: 20%
553 margin: 0
910d631b 554
0e16cb26
BA
555#turnIndicator
556 text-align: center
29bc61be 557 font-weight: bold
910d631b 558
bd76b456
BA
559#belowControls
560 border-top: 1px solid #2f4f4f
cf94b843 561 text-align: center
bd76b456
BA
562 margin: 0 auto
563 & > #downloadDiv
564 margin: 0
565 & > button
566 margin: 0
567 & > button
568 border-left: 1px solid #2f4f4f
569 margin: 0
910d631b 570
72ccbd67 571#boardContainer
cf94b843 572 float: left
41c80bb6
BA
573// TODO: later, maybe, allow movesList of variable width
574// or e.g. between 250 and 350px (but more complicated)
910d631b 575
cf94b843
BA
576#movesList
577 width: 280px
578 float: left
910d631b 579
96e9585a
BA
580@media screen and (max-width: 767px)
581 #movesList
582 width: 100%
583 float: none
584 clear: both
72ccbd67 585</style>