Improve style
[vchess.git] / client / src / components / BaseGame.vue
1 <template lang="pug">
2 div#baseGame
3 input#modalEog.modal(type="checkbox")
4 div#eogDiv(
5 role="dialog"
6 data-checkbox="modalEog"
7 )
8 .card.text-center
9 label.modal-close(for="modalEog")
10 h3.section {{ endgameMessage }}
11 input#modalAdjust.modal(type="checkbox")
12 div#adjuster(
13 role="dialog"
14 data-checkbox="modalAdjust"
15 )
16 .card.text-center
17 label.modal-close(for="modalAdjust")
18 label(for="boardSize") {{ st.tr["Board size"] }}
19 input#boardSize.slider(
20 type="range"
21 min="0"
22 max="100"
23 value="50"
24 @input="adjustBoard()"
25 )
26 #gameContainer
27 #boardContainer
28 Board(
29 :vr="vr"
30 :last-move="lastMove"
31 :analyze="game.mode=='analyze'"
32 :score="game.score"
33 :user-color="game.mycolor"
34 :orientation="orientation"
35 :vname="game.vname"
36 :incheck="incheck"
37 @play-move="play"
38 )
39 #turnIndicator(v-if="showTurn") {{ turn }}
40 #controls
41 button(@click="gotoBegin()") <<
42 button(@click="undo()") <
43 button(v-if="canFlip" @click="flip()") &#8645;
44 button(@click="play()") >
45 button(@click="gotoEnd()") >>
46 #belowControls
47 #downloadDiv(v-if="allowDownloadPGN")
48 a#download(href="#")
49 button(@click="download()") {{ st.tr["Download"] }} PGN
50 button(onClick="window.doClick('modalAdjust')") &#10530;
51 button(
52 v-if="canAnalyze"
53 @click="analyzePosition()"
54 )
55 | {{ st.tr["Analyse"] }}
56 // NOTE: variants pages already have a "Rules" link on top
57 button(
58 v-if="!$route.path.match('/variants/')"
59 @click="showRules()"
60 )
61 | {{ st.tr["Rules"] }}
62 #movesList
63 MoveList(
64 v-if="showMoves != 'none'"
65 :show="showMoves"
66 :score="game.score"
67 :message="game.scoreMsg"
68 :firstNum="firstMoveNumber"
69 :moves="moves"
70 :cursor="cursor"
71 @goto-move="gotoMove"
72 )
73 .clearer
74 </template>
75
76 <script>
77 import Board from "@/components/Board.vue";
78 import MoveList from "@/components/MoveList.vue";
79 import { store } from "@/store";
80 import { getSquareId } from "@/utils/squareId";
81 import { getDate } from "@/utils/datetime";
82 import { processModalClick } from "@/utils/modalClick";
83 import { getScoreMessage } from "@/utils/scoring";
84 import { getFullNotation } from "@/utils/notation";
85 import { undoMove } from "@/utils/playUndo";
86 export default {
87 name: "my-base-game",
88 components: {
89 Board,
90 MoveList
91 },
92 props: ["game"],
93 data: function() {
94 return {
95 st: store.state,
96 // NOTE: all following variables must be reset at the beginning of a game
97 vr: null, //VariantRules object, game state
98 endgameMessage: "",
99 orientation: "w",
100 score: "*", //'*' means 'unfinished'
101 moves: [],
102 // TODO: later, use subCursor to navigate intra-multimoves?
103 cursor: -1, //index of the move just played
104 lastMove: null,
105 firstMoveNumber: 0, //for printing
106 incheck: [], //for Board
107 inMultimove: false
108 };
109 },
110 watch: {
111 // game initial FEN changes when a new game starts
112 "game.fenStart": function() {
113 this.re_setVariables();
114 },
115 },
116 computed: {
117 showMoves: function() {
118 return this.game.score != "*"
119 ? "all"
120 : (this.vr ? this.vr.showMoves : "none");
121 },
122 showTurn: function() {
123 return (
124 this.game.score == '*' &&
125 this.vr &&
126 (this.vr.showMoves != "all" || !this.vr.canFlip)
127 );
128 },
129 turn: function() {
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!"]
137 : "";
138 },
139 canAnalyze: function() {
140 return this.game.mode != "analyze" && this.vr && this.vr.canAnalyze;
141 },
142 canFlip: function() {
143 return this.vr && this.vr.canFlip;
144 },
145 allowDownloadPGN: function() {
146 return this.game.score != "*" || (this.vr && this.vr.showMoves == "all");
147 }
148 },
149 created: function() {
150 if (this.game.fenStart) this.re_setVariables();
151 },
152 mounted: function() {
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 }
161 [
162 document.getElementById("eogDiv"),
163 document.getElementById("adjuster")
164 ].forEach(elt => elt.addEventListener("click", processModalClick));
165 // Take full width on small screens:
166 let boardSize = parseInt(localStorage.getItem("boardSize"));
167 if (!boardSize) {
168 boardSize =
169 window.innerWidth >= 768
170 ? 0.75 * Math.min(window.innerWidth, window.innerHeight)
171 : window.innerWidth;
172 }
173 const movesWidth = window.innerWidth >= 768 ? 280 : 0;
174 document.getElementById("boardContainer").style.width = boardSize + "px";
175 let gameContainer = document.getElementById("gameContainer");
176 gameContainer.style.width = boardSize + movesWidth + "px";
177 document.getElementById("boardSize").value =
178 (boardSize * 100) / (window.innerWidth - movesWidth);
179 // timeout to avoid calling too many time the adjust method
180 let timeoutLaunched = false;
181 window.addEventListener("resize", () => {
182 if (!timeoutLaunched) {
183 timeoutLaunched = true;
184 setTimeout(() => {
185 this.adjustBoard();
186 timeoutLaunched = false;
187 }, 500);
188 }
189 });
190 },
191 methods: {
192 focusBg: function() {
193 document.getElementById("baseGame").focus();
194 },
195 adjustBoard: function() {
196 const boardContainer = document.getElementById("boardContainer");
197 if (!boardContainer) return; //no board on page
198 const k = document.getElementById("boardSize").value;
199 const movesWidth = window.innerWidth >= 768 ? 280 : 0;
200 const minBoardWidth = 240; //TODO: these 240 and 280 are arbitrary...
201 // Value of 0 is board min size; 100 is window.width [- movesWidth]
202 const boardSize =
203 minBoardWidth +
204 (k * (window.innerWidth - (movesWidth + minBoardWidth))) / 100;
205 localStorage.setItem("boardSize", boardSize);
206 boardContainer.style.width = boardSize + "px";
207 document.getElementById("gameContainer").style.width =
208 boardSize + movesWidth + "px";
209 },
210 handleKeys: function(e) {
211 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
212 switch (e.keyCode) {
213 case 37:
214 this.undo();
215 break;
216 case 39:
217 this.play();
218 break;
219 case 38:
220 this.gotoBegin();
221 break;
222 case 40:
223 this.gotoEnd();
224 break;
225 case 32:
226 this.flip();
227 break;
228 }
229 },
230 handleScroll: function(e) {
231 e.preventDefault();
232 if (e.deltaY < 0) this.undo();
233 else if (e.deltaY > 0) this.play();
234 },
235 showRules: function() {
236 //this.$router.push("/variants/" + this.game.vname);
237 window.open("#/variants/" + this.game.vname, "_blank"); //better
238 },
239 re_setVariables: function() {
240 this.endgameMessage = "";
241 // "w": default orientation for observed games
242 this.orientation = this.game.mycolor || "w";
243 this.moves = JSON.parse(JSON.stringify(this.game.moves || []));
244 // Post-processing: decorate each move with notation and FEN
245 this.vr = new V(this.game.fenStart);
246 const parsedFen = V.ParseFen(this.game.fenStart);
247 const firstMoveColor = parsedFen.turn;
248 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2);
249 this.moves.forEach(move => {
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 });
256 });
257 if (firstMoveColor == "b") {
258 // 'start' & 'end' is required for Board component
259 this.moves.unshift({
260 notation: "...",
261 start: { x: -1, y: -1 },
262 end: { x: -1, y: -1 }
263 });
264 }
265 this.positionCursorTo(this.moves.length - 1);
266 this.incheck = this.vr.getCheckSquares(this.vr.turn);
267 },
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 },
282 analyzePosition: function() {
283 const newUrl =
284 "/analyse/" +
285 this.game.vname +
286 "/?fen=" +
287 this.vr.getFen().replace(/ /g, "_");
288 // Open in same tab in live games (against cheating)
289 if (this.game.type == "live") this.$router.push(newUrl);
290 else window.open("#" + newUrl);
291 },
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");
297 downloadAnchor.href =
298 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
299 downloadAnchor.click();
300 },
301 getPgn: function() {
302 let pgn = "";
303 pgn += '[Site "vchess.club"]\n';
304 pgn += '[Variant "' + this.game.vname + '"]\n';
305 pgn += '[Date "' + getDate(new Date()) + '"]\n';
306 pgn += '[White "' + this.game.players[0].name + '"]\n';
307 pgn += '[Black "' + this.game.players[1].name + '"]\n';
308 pgn += '[Fen "' + this.game.fenStart + '"]\n';
309 pgn += '[Result "' + this.game.score + '"]\n\n';
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]) + " ";
314 }
315 return pgn + "\n";
316 },
317 showEndgameMsg: function(message) {
318 this.endgameMessage = message;
319 let modalBox = document.getElementById("modalEog");
320 modalBox.checked = true;
321 setTimeout(() => {
322 modalBox.checked = false;
323 }, 2000);
324 },
325 // Animate an elementary move
326 animateMove: function(move, callback) {
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();
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 );
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");
341 for (let i = 0; i < squares.length; i++) {
342 let square = squares.item(i);
343 if (square.id != getSquareId(move.start)) square.style.zIndex = "-1";
344 }
345 movingPiece.style.transform =
346 "translate(" + translation.x + "px," + translation.y + "px)";
347 movingPiece.style.transitionDuration = "0.25s";
348 movingPiece.style.zIndex = "3000";
349 setTimeout(() => {
350 for (let i = 0; i < squares.length; i++)
351 squares.item(i).style.zIndex = "auto";
352 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
353 callback();
354 }, 250);
355 },
356 // "light": if gotoMove() or gotoEnd()
357 // data: some custom data (addTime) to be re-emitted
358 play: function(move, received, light, data) {
359 const navigate = !move;
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)
417 else this.showEndgameMsg(score + " . " + this.st.tr[message]);
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 }
440 // Forbid playing outside analyze mode, except if move is received.
441 // Sufficient condition because Board already knows which turn it is.
442 if (
443 this.game.mode != "analyze" &&
444 !received &&
445 (this.game.score != "*" || this.cursor < this.moves.length - 1)
446 ) {
447 return;
448 }
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();
473 this.incheck = this.vr.getCheckSquares(this.vr.turn);
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);
487 }
488 }
489 },
490 gotoMove: function(index) {
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);
504 this.incheck = this.vr.getCheckSquares(this.vr.turn);
505 },
506 gotoBegin: function() {
507 if (this.inMultimove) this.cancelCurrentMultimove();
508 while (this.cursor >= 0)
509 this.undo(null, null, "light");
510 if (this.moves.length > 0 && this.moves[0].notation == "...") {
511 this.cursor = 0;
512 this.lastMove = this.moves[0];
513 } else {
514 this.lastMove = null;
515 }
516 this.incheck = [];
517 },
518 gotoEnd: function() {
519 if (this.cursor == this.moves.length - 1) return;
520 this.gotoMove(this.moves.length - 1);
521 },
522 flip: function() {
523 this.orientation = V.GetOppCol(this.orientation);
524 }
525 }
526 };
527 </script>
528
529 <style lang="sass" scoped>
530 [type="checkbox"]#modalEog+div .card
531 min-height: 45px
532
533 [type="checkbox"]#modalAdjust+div .card
534 padding: 5px
535
536 #baseGame
537 width: 100%
538 &:focus
539 outline: none
540
541 #gameContainer
542 margin-left: auto
543 margin-right: auto
544
545 #downloadDiv
546 display: inline-block
547
548 #controls
549 margin: 0 auto
550 text-align: center
551 button
552 display: inline-block
553 width: 20%
554 margin: 0
555
556 #turnIndicator
557 text-align: center
558 font-weight: bold
559
560 #belowControls
561 border-top: 1px solid #2f4f4f
562 text-align: center
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
571
572 #boardContainer
573 float: left
574 // TODO: later, maybe, allow movesList of variable width
575 // or e.g. between 250 and 350px (but more complicated)
576
577 #movesList
578 width: 280px
579 float: left
580
581 @media screen and (max-width: 767px)
582 #movesList
583 width: 100%
584 float: none
585 clear: both
586 </style>