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