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