Implemented multi-move possibility in a moves list => better support for multi-moves...
[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 input#modalAdjust.modal(type="checkbox")
12 div#adjuster(
13 role="dialog"
14 data-checkbox="modalAdjust"
15 )
16 .card.text-center
17 label.modal-close(for="modalAdjust")
18 label(for="boardSize") {{ st.tr["Board size"] }}
19 input#boardSize.slider(
20 type="range"
21 min="0"
22 max="100"
23 value="50"
24 @input="adjustBoard()"
25 )
26 #gameContainer
27 #boardContainer
28 Board(
29 :vr="vr"
30 :last-move="lastMove"
31 :analyze="game.mode=='analyze'"
32 :score="game.score"
33 :user-color="game.mycolor"
34 :orientation="orientation"
35 :vname="game.vname"
36 :incheck="incheck"
37 @play-move="play"
38 )
39 #turnIndicator(v-if="showTurn") {{ turn }}
40 #controls
41 button(@click="gotoBegin()") <<
42 button(@click="undo()") <
43 button(v-if="canFlip" @click="flip()") &#8645;
44 button(@click="play()") >
45 button(@click="gotoEnd()") >>
46 #belowControls
47 #downloadDiv(v-if="allowDownloadPGN")
48 a#download(href="#")
49 button(@click="download()") {{ st.tr["Download"] }} PGN
50 button(onClick="window.doClick('modalAdjust')") &#10530;
51 button(
52 v-if="canAnalyze"
53 @click="analyzePosition()"
54 )
55 | {{ st.tr["Analyse"] }}
56 // NOTE: variants pages already have a "Rules" link on top
57 button(
58 v-if="!$route.path.match('/variants/')"
59 @click="showRules()"
60 )
61 | {{ st.tr["Rules"] }}
62 #movesList
63 MoveList(
64 v-if="showMoves != 'none'"
65 :show="showMoves"
66 :score="game.score"
67 :message="game.scoreMsg"
68 :firstNum="firstMoveNumber"
69 :moves="moves"
70 :cursor="cursor"
71 @goto-move="gotoMove"
72 )
73 .clearer
74 </template>
75
76 <script>
77 import Board from "@/components/Board.vue";
78 import MoveList from "@/components/MoveList.vue";
79 import { store } from "@/store";
80 import { getSquareId } from "@/utils/squareId";
81 import { getDate } from "@/utils/datetime";
82 import { processModalClick } from "@/utils/modalClick";
83 import { getScoreMessage } from "@/utils/scoring";
84 import { getFullNotation } from "@/utils/notation";
85 import { undoMove } from "@/utils/playUndo";
86 export default {
87 name: "my-base-game",
88 components: {
89 Board,
90 MoveList
91 },
92 props: ["game"],
93 data: function() {
94 return {
95 st: store.state,
96 // NOTE: all following variables must be reset at the beginning of a game
97 vr: null, //VariantRules object, game state
98 endgameMessage: "",
99 orientation: "w",
100 score: "*", //'*' means 'unfinished'
101 moves: [],
102 // TODO: later, use subCursor to navigate intra-multimoves?
103 cursor: -1, //index of the move just played
104 lastMove: null,
105 firstMoveNumber: 0, //for printing
106 incheck: [], //for Board
107 inMultimove: false
108 };
109 },
110 watch: {
111 // game initial FEN changes when a new game starts
112 "game.fenStart": function() {
113 this.re_setVariables();
114 },
115 },
116 computed: {
117 showMoves: function() {
118 return this.game.score != "*"
119 ? "all"
120 : (this.vr ? this.vr.showMoves : "none");
121 },
122 showTurn: function() {
123 return (
124 this.game.score == '*' &&
125 this.vr &&
126 (this.vr.showMoves != "all" || !this.vr.canFlip)
127 );
128 },
129 turn: function() {
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!"]
137 : "";
138 },
139 canAnalyze: function() {
140 return this.game.mode != "analyze" && this.vr && this.vr.canAnalyze;
141 },
142 canFlip: function() {
143 return this.vr && this.vr.canFlip;
144 },
145 allowDownloadPGN: function() {
146 return this.game.score != "*" || (this.vr && this.vr.showMoves == "all");
147 }
148 },
149 created: function() {
150 if (this.game.fenStart) this.re_setVariables();
151 },
152 mounted: function() {
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 }
161 [
162 document.getElementById("eogDiv"),
163 document.getElementById("adjuster")
164 ].forEach(elt => elt.addEventListener("click", processModalClick));
165 // Take full width on small screens:
166 let boardSize = parseInt(localStorage.getItem("boardSize"));
167 if (!boardSize) {
168 boardSize =
169 window.innerWidth >= 768
170 ? 0.75 * Math.min(window.innerWidth, window.innerHeight)
171 : window.innerWidth;
172 }
173 const movesWidth = window.innerWidth >= 768 ? 280 : 0;
174 document.getElementById("boardContainer").style.width = boardSize + "px";
175 let gameContainer = document.getElementById("gameContainer");
176 gameContainer.style.width = boardSize + movesWidth + "px";
177 document.getElementById("boardSize").value =
178 (boardSize * 100) / (window.innerWidth - movesWidth);
179 // timeout to avoid calling too many time the adjust method
180 let timeoutLaunched = false;
181 window.addEventListener("resize", () => {
182 if (!timeoutLaunched) {
183 timeoutLaunched = true;
184 setTimeout(() => {
185 this.adjustBoard();
186 timeoutLaunched = false;
187 }, 500);
188 }
189 });
190 },
191 methods: {
192 focusBg: function() {
193 document.getElementById("baseGame").focus();
194 },
195 adjustBoard: function() {
196 const boardContainer = document.getElementById("boardContainer");
197 if (!boardContainer) return; //no board on page
198 const k = document.getElementById("boardSize").value;
199 const movesWidth = window.innerWidth >= 768 ? 280 : 0;
200 const minBoardWidth = 240; //TODO: these 240 and 280 are arbitrary...
201 // Value of 0 is board min size; 100 is window.width [- movesWidth]
202 const boardSize =
203 minBoardWidth +
204 (k * (window.innerWidth - (movesWidth + minBoardWidth))) / 100;
205 localStorage.setItem("boardSize", boardSize);
206 boardContainer.style.width = boardSize + "px";
207 document.getElementById("gameContainer").style.width =
208 boardSize + movesWidth + "px";
209 },
210 handleKeys: function(e) {
211 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
212 switch (e.keyCode) {
213 case 37:
214 this.undo();
215 break;
216 case 39:
217 this.play();
218 break;
219 case 38:
220 this.gotoBegin();
221 break;
222 case 40:
223 this.gotoEnd();
224 break;
225 case 32:
226 this.flip();
227 break;
228 }
229 },
230 handleScroll: function(e) {
231 e.preventDefault();
232 if (e.deltaY < 0) this.undo();
233 else if (e.deltaY > 0) this.play();
234 },
235 showRules: function() {
236 //this.$router.push("/variants/" + this.game.vname);
237 window.open("#/variants/" + this.game.vname, "_blank"); //better
238 },
239 re_setVariables: function() {
240 this.endgameMessage = "";
241 // "w": default orientation for observed games
242 this.orientation = this.game.mycolor || "w";
243 this.moves = JSON.parse(JSON.stringify(this.game.moves || []));
244 // Post-processing: decorate each move with notation and FEN
245 this.vr = new V(this.game.fenStart);
246 const parsedFen = V.ParseFen(this.game.fenStart);
247 const firstMoveColor = parsedFen.turn;
248 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2);
249 this.moves.forEach(move => {
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 });
256 });
257 if (firstMoveColor == "b") {
258 // 'end' is required for Board component to check lastMove for e.p.
259 this.moves.unshift({
260 notation: "...",
261 end: { x: -1, y: -1 }
262 });
263 }
264 this.positionCursorTo(this.moves.length - 1);
265 this.incheck = this.vr.getCheckSquares(this.vr.turn);
266 },
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 },
281 analyzePosition: function() {
282 const newUrl =
283 "/analyse/" +
284 this.game.vname +
285 "/?fen=" +
286 this.vr.getFen().replace(/ /g, "_");
287 // Open in same tab in live games (against cheating)
288 if (this.game.type == "live") this.$router.push(newUrl);
289 else window.open("#" + newUrl);
290 },
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");
296 downloadAnchor.href =
297 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
298 downloadAnchor.click();
299 },
300 getPgn: function() {
301 let pgn = "";
302 pgn += '[Site "vchess.club"]\n';
303 pgn += '[Variant "' + this.game.vname + '"]\n';
304 pgn += '[Date "' + getDate(new Date()) + '"]\n';
305 pgn += '[White "' + this.game.players[0].name + '"]\n';
306 pgn += '[Black "' + this.game.players[1].name + '"]\n';
307 pgn += '[Fen "' + this.game.fenStart + '"]\n';
308 pgn += '[Result "' + this.game.score + '"]\n\n';
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]) + " ";
313 }
314 return pgn + "\n";
315 },
316 showEndgameMsg: function(message) {
317 this.endgameMessage = message;
318 let modalBox = document.getElementById("modalEog");
319 modalBox.checked = true;
320 setTimeout(() => {
321 modalBox.checked = false;
322 }, 2000);
323 },
324 // Animate an elementary move
325 animateMove: function(move, callback) {
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();
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 );
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");
340 for (let i = 0; i < squares.length; i++) {
341 let square = squares.item(i);
342 if (square.id != getSquareId(move.start)) square.style.zIndex = "-1";
343 }
344 movingPiece.style.transform =
345 "translate(" + translation.x + "px," + translation.y + "px)";
346 movingPiece.style.transitionDuration = "0.25s";
347 movingPiece.style.zIndex = "3000";
348 setTimeout(() => {
349 for (let i = 0; i < squares.length; i++)
350 squares.item(i).style.zIndex = "auto";
351 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
352 callback();
353 }, 250);
354 },
355 // "light": if gotoMove() or gotoEnd()
356 // data: some custom data (addTime) to be re-emitted
357 play: function(move, received, light, data) {
358 const navigate = !move;
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 }
439 // Forbid playing outside analyze mode, except if move is received.
440 // Sufficient condition because Board already knows which turn it is.
441 if (
442 this.game.mode != "analyze" &&
443 !received &&
444 (this.game.score != "*" || this.cursor < this.moves.length - 1)
445 ) {
446 return;
447 }
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();
472 this.incheck = this.vr.getCheckSquares(this.vr.turn);
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);
486 }
487 }
488 },
489 gotoMove: function(index) {
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);
503 this.incheck = this.vr.getCheckSquares(this.vr.turn);
504 },
505 gotoBegin: function() {
506 if (this.inMultimove) this.cancelCurrentMultimove();
507 while (this.cursor >= 0)
508 this.undo(null, null, "light");
509 if (this.moves.length > 0 && this.moves[0].notation == "...") {
510 this.cursor = 0;
511 this.lastMove = this.moves[0];
512 } else {
513 this.lastMove = null;
514 }
515 this.incheck = [];
516 },
517 gotoEnd: function() {
518 if (this.cursor == this.moves.length - 1) return;
519 this.gotoMove(this.moves.length - 1);
520 },
521 flip: function() {
522 this.orientation = V.GetOppCol(this.orientation);
523 }
524 }
525 };
526 </script>
527
528 <style lang="sass" scoped>
529 [type="checkbox"]#modalEog+div .card
530 min-height: 45px
531
532 [type="checkbox"]#modalAdjust+div .card
533 padding: 5px
534
535 #baseGame
536 width: 100%
537 &:focus
538 outline: none
539
540 #gameContainer
541 margin-left: auto
542 margin-right: auto
543
544 #downloadDiv
545 display: inline-block
546
547 #controls
548 margin: 0 auto
549 text-align: center
550 button
551 display: inline-block
552 width: 20%
553 margin: 0
554
555 #turnIndicator
556 text-align: center
557 font-weight: bold
558
559 #belowControls
560 border-top: 1px solid #2f4f4f
561 text-align: center
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
570
571 #boardContainer
572 float: left
573 // TODO: later, maybe, allow movesList of variable width
574 // or e.g. between 250 and 350px (but more complicated)
575
576 #movesList
577 width: 280px
578 float: left
579
580 @media screen and (max-width: 767px)
581 #movesList
582 width: 100%
583 float: none
584 clear: both
585 </style>