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