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