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