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