Improve style
[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") {
311cba76 258 // 'start' & 'end' is required for Board component
6808d7a1 259 this.moves.unshift({
6808d7a1 260 notation: "...",
311cba76 261 start: { x: -1, y: -1 },
6808d7a1
BA
262 end: { x: -1, y: -1 }
263 });
697ee580 264 }
e71161fb 265 this.positionCursorTo(this.moves.length - 1);
9ef63965 266 this.incheck = this.vr.getCheckSquares(this.vr.turn);
4b0384fa 267 },
e71161fb
BA
268 positionCursorTo: function(index) {
269 this.cursor = index;
270 // Caution: last move in moves array might be a multi-move
271 if (index >= 0) {
272 if (Array.isArray(this.moves[index])) {
273 const L = this.moves[index].length;
274 this.lastMove = this.moves[index][L - 1];
275 } else {
276 this.lastMove = this.moves[index];
277 }
278 }
279 else
280 this.lastMove = null;
281 },
63ca2b89 282 analyzePosition: function() {
6808d7a1
BA
283 const newUrl =
284 "/analyse/" +
285 this.game.vname +
286 "/?fen=" +
287 this.vr.getFen().replace(/ /g, "_");
910d631b 288 // Open in same tab in live games (against cheating)
6808d7a1 289 if (this.game.type == "live") this.$router.push(newUrl);
910d631b 290 else window.open("#" + newUrl);
603b8a8b 291 },
a6088c90
BA
292 download: function() {
293 const content = this.getPgn();
294 // Prepare and trigger download link
295 let downloadAnchor = document.getElementById("download");
296 downloadAnchor.setAttribute("download", "game.pgn");
6808d7a1
BA
297 downloadAnchor.href =
298 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
a6088c90
BA
299 downloadAnchor.click();
300 },
301 getPgn: function() {
302 let pgn = "";
303 pgn += '[Site "vchess.club"]\n';
834c202a 304 pgn += '[Variant "' + this.game.vname + '"]\n';
a6088c90 305 pgn += '[Date "' + getDate(new Date()) + '"]\n';
d4036efe
BA
306 pgn += '[White "' + this.game.players[0].name + '"]\n';
307 pgn += '[Black "' + this.game.players[1].name + '"]\n';
834c202a 308 pgn += '[Fen "' + this.game.fenStart + '"]\n';
430a2038 309 pgn += '[Result "' + this.game.score + '"]\n\n';
e71161fb
BA
310 for (let i = 0; i < this.moves.length; i += 2) {
311 pgn += (i/2+1) + "." + getFullNotation(this.moves[i]) + " ";
312 if (i+1 < this.moves.length)
313 pgn += getFullNotation(this.moves[i+1]) + " ";
a6088c90
BA
314 }
315 return pgn + "\n";
316 },
b988c726
BA
317 showEndgameMsg: function(message) {
318 this.endgameMessage = message;
4494c17c 319 let modalBox = document.getElementById("modalEog");
a6088c90 320 modalBox.checked = true;
6808d7a1
BA
321 setTimeout(() => {
322 modalBox.checked = false;
323 }, 2000);
a6088c90 324 },
e71161fb 325 // Animate an elementary move
63ca2b89 326 animateMove: function(move, callback) {
a6088c90
BA
327 let startSquare = document.getElementById(getSquareId(move.start));
328 let endSquare = document.getElementById(getSquareId(move.end));
329 let rectStart = startSquare.getBoundingClientRect();
330 let rectEnd = endSquare.getBoundingClientRect();
6808d7a1
BA
331 let translation = {
332 x: rectEnd.x - rectStart.x,
333 y: rectEnd.y - rectStart.y
334 };
335 let movingPiece = document.querySelector(
336 "#" + getSquareId(move.start) + " > img.piece"
337 );
a6088c90
BA
338 // HACK for animation (with positive translate, image slides "under background")
339 // Possible improvement: just alter squares on the piece's way...
340 const squares = document.getElementsByClassName("board");
6808d7a1 341 for (let i = 0; i < squares.length; i++) {
a6088c90 342 let square = squares.item(i);
6808d7a1 343 if (square.id != getSquareId(move.start)) square.style.zIndex = "-1";
a6088c90 344 }
6808d7a1
BA
345 movingPiece.style.transform =
346 "translate(" + translation.x + "px," + translation.y + "px)";
910d631b 347 movingPiece.style.transitionDuration = "0.25s";
a6088c90 348 movingPiece.style.zIndex = "3000";
6808d7a1
BA
349 setTimeout(() => {
350 for (let i = 0; i < squares.length; i++)
a6088c90
BA
351 squares.item(i).style.zIndex = "auto";
352 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
63ca2b89 353 callback();
a6088c90
BA
354 }, 250);
355 },
e71161fb
BA
356 // "light": if gotoMove() or gotoEnd()
357 // data: some custom data (addTime) to be re-emitted
358 play: function(move, received, light, data) {
9d54ab89 359 const navigate = !move;
e71161fb
BA
360 const playSubmove = (smove) => {
361 if (!navigate) smove.notation = this.vr.getNotation(smove);
362 this.vr.play(smove);
363 this.lastMove = smove;
364 // Is opponent in check?
365 this.incheck = this.vr.getCheckSquares(this.vr.turn);
366 if (!navigate) {
367 if (!this.inMultimove) {
368 if (this.cursor < this.moves.length - 1)
369 this.moves = this.moves.slice(0, Math.max(this.cursor, 0));
370 this.moves.push(smove);
371 this.inMultimove = true; //potentially
372 this.cursor++;
373 } else {
374 // Already in the middle of a multi-move
375 const L = this.moves.length;
376 if (!Array.isArray(this.moves[L-1]))
377 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
378 else
379 this.$set(this.moves, L-1, this.moves.concat([smove]));
380 }
381 }
382 };
383 const playMove = () => {
384 const animate = V.ShowMoves == "all" && received;
385 if (!Array.isArray(move)) move = [move];
386 let moveIdx = 0;
387 let self = this;
388 const initurn = this.vr.turn;
389 (function executeMove() {
390 const smove = move[moveIdx++];
391 if (animate) {
392 self.animateMove(smove, () => {
393 playSubmove(smove);
394 if (moveIdx < move.length)
395 setTimeout(executeMove, 500);
396 else afterMove(smove, initurn);
397 });
398 } else {
399 playSubmove(smove);
400 if (moveIdx < move.length) executeMove();
401 else afterMove(smove, initurn);
402 }
403 })();
404 };
405 const afterMove = (smove, initurn) => {
406 if (this.st.settings.sound == 2)
407 new Audio("/sounds/move.mp3").play().catch(() => {});
408 if (this.vr.turn != initurn) {
409 // Turn has changed: move is complete
410 this.inMultimove = false;
411 const score = this.vr.getCurrentScore();
412 if (score != "*") {
413 const message = getScoreMessage(score);
414 if (!navigate && this.game.mode != "analyze")
415 this.$emit("gameover", score, message);
416 // Just show score on screen (allow undo)
311cba76 417 else this.showEndgameMsg(score + " . " + this.st.tr[message]);
e71161fb
BA
418 }
419 if (!navigate && this.game.mode != "analyze") {
420 const L = this.moves.length;
421 // Post-processing (e.g. computer play)
422 this.$emit("newmove", this.moves[L-1], data);
423 }
424 }
425 };
426 // NOTE: navigate and received are mutually exclusive
427 if (navigate) {
428 // The move to navigate to is necessarily full:
429 if (this.cursor == this.moves.length - 1) return; //no more moves
430 move = this.moves[this.cursor + 1];
431 if (light) {
432 // Just play the move, nothing else:
433 if (!Array.isArray(move)) move = [move];
434 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
435 }
436 else playMove();
437 this.cursor++;
438 return;
439 }
63ca2b89
BA
440 // Forbid playing outside analyze mode, except if move is received.
441 // Sufficient condition because Board already knows which turn it is.
6808d7a1 442 if (
6808d7a1 443 this.game.mode != "analyze" &&
e71161fb 444 !received &&
6808d7a1
BA
445 (this.game.score != "*" || this.cursor < this.moves.length - 1)
446 ) {
a6088c90
BA
447 return;
448 }
e71161fb
BA
449 // To play a received move, cursor must be at the end of the game:
450 if (received && this.cursor < this.moves.length - 1)
451 this.gotoEnd();
452 playMove();
453 },
454 cancelCurrentMultimove: function() {
455 // Cancel current multi-move
456 const L = this.moves.length;
457 let move = this.moves[L-1];
458 if (!Array.isArray(move)) move = [move];
459 for (let i=move.length -1; i >= 0; i--) this.vr.undo(move[i]);
460 this.moves.pop();
461 this.cursor--;
462 this.inMultimove = false;
463 },
464 cancelLastMove: function() {
465 // The last played move was canceled (corr game)
466 this.undo();
467 this.moves.pop();
468 },
469 // "light": if gotoMove() or gotoBegin()
470 undo: function(move, light) {
471 if (this.inMultimove) {
472 this.cancelCurrentMultimove();
63ca2b89 473 this.incheck = this.vr.getCheckSquares(this.vr.turn);
e71161fb
BA
474 } else {
475 if (!move) {
476 if (this.cursor < 0) return; //no more moves
477 move = this.moves[this.cursor];
478 }
479 // Caution; if multi-move, undo all submoves from last to first
480 undoMove(move, this.vr);
481 if (light) this.cursor--;
482 else {
483 this.positionCursorTo(this.cursor - 1);
484 if (this.st.settings.sound == 2)
485 new Audio("/sounds/undo.mp3").play().catch(() => {});
486 this.incheck = this.vr.getCheckSquares(this.vr.turn);
63ca2b89 487 }
a6088c90 488 }
a6088c90
BA
489 },
490 gotoMove: function(index) {
e71161fb
BA
491 if (this.inMultimove) this.cancelCurrentMultimove();
492 if (index == this.cursor) return;
493 if (index < this.cursor) {
494 while (this.cursor > index)
495 this.undo(null, null, "light");
496 }
497 else {
498 // index > this.cursor)
499 while (this.cursor < index)
500 this.play(null, null, "light");
501 }
502 // NOTE: next line also re-assign cursor, but it's very light
503 this.positionCursorTo(index);
8b405c81 504 this.incheck = this.vr.getCheckSquares(this.vr.turn);
a6088c90
BA
505 },
506 gotoBegin: function() {
e71161fb
BA
507 if (this.inMultimove) this.cancelCurrentMultimove();
508 while (this.cursor >= 0)
509 this.undo(null, null, "light");
6808d7a1 510 if (this.moves.length > 0 && this.moves[0].notation == "...") {
5701c228
BA
511 this.cursor = 0;
512 this.lastMove = this.moves[0];
6808d7a1 513 } else {
5701c228
BA
514 this.lastMove = null;
515 }
e71161fb 516 this.incheck = [];
a6088c90
BA
517 },
518 gotoEnd: function() {
6808d7a1
BA
519 if (this.cursor == this.moves.length - 1) return;
520 this.gotoMove(this.moves.length - 1);
a6088c90
BA
521 },
522 flip: function() {
0e16cb26 523 this.orientation = V.GetOppCol(this.orientation);
6808d7a1
BA
524 }
525 }
a6088c90
BA
526};
527</script>
72ccbd67 528
41c80bb6 529<style lang="sass" scoped>
9a3049f3
BA
530[type="checkbox"]#modalEog+div .card
531 min-height: 45px
910d631b 532
9a3049f3
BA
533[type="checkbox"]#modalAdjust+div .card
534 padding: 5px
535
cf94b843
BA
536#baseGame
537 width: 100%
4f518610
BA
538 &:focus
539 outline: none
cf94b843
BA
540
541#gameContainer
72ccbd67
BA
542 margin-left: auto
543 margin-right: auto
cf94b843 544
ed06d9e9
BA
545#downloadDiv
546 display: inline-block
547
72ccbd67 548#controls
bd76b456 549 margin: 0 auto
71ef1664 550 text-align: center
72ccbd67
BA
551 button
552 display: inline-block
553 width: 20%
554 margin: 0
910d631b 555
0e16cb26
BA
556#turnIndicator
557 text-align: center
29bc61be 558 font-weight: bold
910d631b 559
bd76b456
BA
560#belowControls
561 border-top: 1px solid #2f4f4f
cf94b843 562 text-align: center
bd76b456
BA
563 margin: 0 auto
564 & > #downloadDiv
565 margin: 0
566 & > button
567 margin: 0
568 & > button
569 border-left: 1px solid #2f4f4f
570 margin: 0
910d631b 571
72ccbd67 572#boardContainer
cf94b843 573 float: left
41c80bb6
BA
574// TODO: later, maybe, allow movesList of variable width
575// or e.g. between 250 and 350px (but more complicated)
910d631b 576
cf94b843
BA
577#movesList
578 width: 280px
579 float: left
910d631b 580
96e9585a
BA
581@media screen and (max-width: 767px)
582 #movesList
583 width: 100%
584 float: none
585 clear: both
72ccbd67 586</style>