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