Show 'resize board' button even in no-information variants
[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 #gameContainer
12 #boardContainer
13 Board(
14 :vr="vr"
15 :last-move="lastMove"
16 :analyze="game.mode=='analyze'"
17 :score="game.score"
18 :user-color="game.mycolor"
19 :orientation="orientation"
20 :vname="game.vname"
21 :incheck="incheck"
22 @play-move="play"
23 )
24 #turnIndicator(v-if="showTurn") {{ turn }}
25 #controls
26 button(@click="gotoBegin()") <<
27 button(@click="undo()") <
28 button(v-if="canFlip" @click="flip()") &#8645;
29 button(@click="play()") >
30 button(@click="gotoEnd()") >>
31 #belowControls
32 #downloadDiv(v-if="allowDownloadPGN")
33 a#download(href="#")
34 button(@click="download()") {{ st.tr["Download"] }} PGN
35 button(
36 v-if="canAnalyze"
37 @click="analyzePosition()"
38 )
39 | {{ st.tr["Analyse"] }}
40 // NOTE: variants pages already have a "Rules" link on top
41 button(
42 v-if="!$route.path.match('/variants/')"
43 @click="showRules()"
44 )
45 | {{ st.tr["Rules"] }}
46 #movesList
47 MoveList(
48 :show="showMoves"
49 :score="game.score"
50 :message="game.scoreMsg"
51 :firstNum="firstMoveNumber"
52 :moves="moves"
53 :cursor="cursor"
54 @goto-move="gotoMove"
55 )
56 .clearer
57 </template>
58
59 <script>
60 import Board from "@/components/Board.vue";
61 import MoveList from "@/components/MoveList.vue";
62 import { store } from "@/store";
63 import { getSquareId } from "@/utils/squareId";
64 import { getDate } from "@/utils/datetime";
65 import { processModalClick } from "@/utils/modalClick";
66 import { getScoreMessage } from "@/utils/scoring";
67 import { getFullNotation } from "@/utils/notation";
68 import { undoMove } from "@/utils/playUndo";
69 export default {
70 name: "my-base-game",
71 components: {
72 Board,
73 MoveList
74 },
75 props: ["game"],
76 data: function() {
77 return {
78 st: store.state,
79 // NOTE: all following variables must be reset at the beginning of a game
80 vr: null, //VariantRules object, game state
81 endgameMessage: "",
82 orientation: "w",
83 score: "*", //'*' means 'unfinished'
84 moves: [],
85 // TODO: later, use subCursor to navigate intra-multimoves?
86 cursor: -1, //index of the move just played
87 lastMove: null,
88 firstMoveNumber: 0, //for printing
89 incheck: [], //for Board
90 inMultimove: false
91 };
92 },
93 watch: {
94 // game initial FEN changes when a new game starts
95 "game.fenStart": function() {
96 this.re_setVariables();
97 },
98 },
99 computed: {
100 showMoves: function() {
101 return this.game.score != "*"
102 ? "all"
103 : (this.vr ? this.vr.showMoves : "none");
104 },
105 showTurn: function() {
106 return (
107 this.game.score == '*' &&
108 this.vr &&
109 (this.vr.showMoves != "all" || !this.vr.canFlip)
110 );
111 },
112 turn: function() {
113 if (!this.vr)
114 return "";
115 if (this.vr.showMoves != "all")
116 return this.st.tr[(this.vr.turn == 'w' ? "White" : "Black") + " to move"]
117 // Cannot flip: racing king or circular chess
118 return this.vr.movesCount == 0 && this.game.mycolor == "w"
119 ? this.st.tr["It's your turn!"]
120 : "";
121 },
122 canAnalyze: function() {
123 return this.game.mode != "analyze" && this.vr && this.vr.canAnalyze;
124 },
125 canFlip: function() {
126 return this.vr && this.vr.canFlip;
127 },
128 allowDownloadPGN: function() {
129 return this.game.score != "*" || (this.vr && this.vr.showMoves == "all");
130 }
131 },
132 created: function() {
133 if (this.game.fenStart) this.re_setVariables();
134 },
135 mounted: function() {
136 if (!("ontouchstart" in window)) {
137 // Desktop browser:
138 const baseGameDiv = document.getElementById("baseGame");
139 baseGameDiv.tabIndex = 0;
140 baseGameDiv.addEventListener("click", this.focusBg);
141 baseGameDiv.addEventListener("keydown", this.handleKeys);
142 baseGameDiv.addEventListener("wheel", this.handleScroll);
143 }
144 document.getElementById("eogDiv").addEventListener(
145 "click",
146 processModalClick);
147 },
148 methods: {
149 focusBg: function() {
150 document.getElementById("baseGame").focus();
151 },
152 handleKeys: function(e) {
153 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
154 switch (e.keyCode) {
155 case 37:
156 this.undo();
157 break;
158 case 39:
159 this.play();
160 break;
161 case 38:
162 this.gotoBegin();
163 break;
164 case 40:
165 this.gotoEnd();
166 break;
167 case 32:
168 this.flip();
169 break;
170 }
171 },
172 handleScroll: function(e) {
173 e.preventDefault();
174 if (e.deltaY < 0) this.undo();
175 else if (e.deltaY > 0) this.play();
176 },
177 showRules: function() {
178 //this.$router.push("/variants/" + this.game.vname);
179 window.open("#/variants/" + this.game.vname, "_blank"); //better
180 },
181 re_setVariables: function() {
182 this.endgameMessage = "";
183 // "w": default orientation for observed games
184 this.orientation = this.game.mycolor || "w";
185 this.moves = JSON.parse(JSON.stringify(this.game.moves || []));
186 // Post-processing: decorate each move with notation and FEN
187 this.vr = new V(this.game.fenStart);
188 const parsedFen = V.ParseFen(this.game.fenStart);
189 const firstMoveColor = parsedFen.turn;
190 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2);
191 this.moves.forEach(move => {
192 // Strategy working also for multi-moves:
193 if (!Array.isArray(move)) move = [move];
194 move.forEach(m => {
195 m.notation = this.vr.getNotation(m);
196 this.vr.play(m);
197 });
198 });
199 if (firstMoveColor == "b") {
200 // 'start' & 'end' is required for Board component
201 this.moves.unshift({
202 notation: "...",
203 start: { x: -1, y: -1 },
204 end: { x: -1, y: -1 }
205 });
206 }
207 this.positionCursorTo(this.moves.length - 1);
208 this.incheck = this.vr.getCheckSquares(this.vr.turn);
209 },
210 positionCursorTo: function(index) {
211 this.cursor = index;
212 // Caution: last move in moves array might be a multi-move
213 if (index >= 0) {
214 if (Array.isArray(this.moves[index])) {
215 const L = this.moves[index].length;
216 this.lastMove = this.moves[index][L - 1];
217 } else {
218 this.lastMove = this.moves[index];
219 }
220 }
221 else
222 this.lastMove = null;
223 },
224 analyzePosition: function() {
225 const newUrl =
226 "/analyse/" +
227 this.game.vname +
228 "/?fen=" +
229 this.vr.getFen().replace(/ /g, "_");
230 // Open in same tab in live games (against cheating)
231 if (this.game.type == "live") this.$router.push(newUrl);
232 else window.open("#" + newUrl);
233 },
234 download: function() {
235 const content = this.getPgn();
236 // Prepare and trigger download link
237 let downloadAnchor = document.getElementById("download");
238 downloadAnchor.setAttribute("download", "game.pgn");
239 downloadAnchor.href =
240 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
241 downloadAnchor.click();
242 },
243 getPgn: function() {
244 let pgn = "";
245 pgn += '[Site "vchess.club"]\n';
246 pgn += '[Variant "' + this.game.vname + '"]\n';
247 pgn += '[Date "' + getDate(new Date()) + '"]\n';
248 pgn += '[White "' + this.game.players[0].name + '"]\n';
249 pgn += '[Black "' + this.game.players[1].name + '"]\n';
250 pgn += '[Fen "' + this.game.fenStart + '"]\n';
251 pgn += '[Result "' + this.game.score + '"]\n\n';
252 for (let i = 0; i < this.moves.length; i += 2) {
253 pgn += (i/2+1) + "." + getFullNotation(this.moves[i]) + " ";
254 if (i+1 < this.moves.length)
255 pgn += getFullNotation(this.moves[i+1]) + " ";
256 }
257 return pgn + "\n";
258 },
259 showEndgameMsg: function(message) {
260 this.endgameMessage = message;
261 let modalBox = document.getElementById("modalEog");
262 modalBox.checked = true;
263 setTimeout(() => {
264 modalBox.checked = false;
265 }, 2000);
266 },
267 // Animate an elementary move
268 animateMove: function(move, callback) {
269 let startSquare = document.getElementById(getSquareId(move.start));
270 let endSquare = document.getElementById(getSquareId(move.end));
271 let rectStart = startSquare.getBoundingClientRect();
272 let rectEnd = endSquare.getBoundingClientRect();
273 let translation = {
274 x: rectEnd.x - rectStart.x,
275 y: rectEnd.y - rectStart.y
276 };
277 let movingPiece = document.querySelector(
278 "#" + getSquareId(move.start) + " > img.piece"
279 );
280 // HACK for animation (with positive translate, image slides "under background")
281 // Possible improvement: just alter squares on the piece's way...
282 const squares = document.getElementsByClassName("board");
283 for (let i = 0; i < squares.length; i++) {
284 let square = squares.item(i);
285 if (square.id != getSquareId(move.start)) square.style.zIndex = "-1";
286 }
287 movingPiece.style.transform =
288 "translate(" + translation.x + "px," + translation.y + "px)";
289 movingPiece.style.transitionDuration = "0.25s";
290 movingPiece.style.zIndex = "3000";
291 setTimeout(() => {
292 for (let i = 0; i < squares.length; i++)
293 squares.item(i).style.zIndex = "auto";
294 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
295 callback();
296 }, 250);
297 },
298 // For Analyse mode:
299 emitFenIfAnalyze: function() {
300 if (this.game.mode == "analyze") {
301 this.$emit(
302 "fenchange",
303 this.lastMove ? this.lastMove.fen : this.game.fenStart
304 );
305 }
306 },
307 // "light": if gotoMove() or gotoEnd()
308 // data: some custom data (addTime) to be re-emitted
309 play: function(move, received, light, data) {
310 const navigate = !move;
311 const playSubmove = (smove) => {
312 if (!navigate) smove.notation = this.vr.getNotation(smove);
313 this.vr.play(smove);
314 this.lastMove = smove;
315 // Is opponent in check?
316 this.incheck = this.vr.getCheckSquares(this.vr.turn);
317 if (!navigate) {
318 if (!this.inMultimove) {
319 if (this.cursor < this.moves.length - 1)
320 this.moves = this.moves.slice(0, this.cursor + 1);
321 this.moves.push(smove);
322 this.inMultimove = true; //potentially
323 this.cursor++;
324 } else {
325 // Already in the middle of a multi-move
326 const L = this.moves.length;
327 if (!Array.isArray(this.moves[L-1]))
328 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
329 else
330 this.$set(this.moves, L-1, this.moves.concat([smove]));
331 }
332 }
333 };
334 const playMove = () => {
335 const animate = V.ShowMoves == "all" && received;
336 if (!Array.isArray(move)) move = [move];
337 let moveIdx = 0;
338 let self = this;
339 const initurn = this.vr.turn;
340 (function executeMove() {
341 const smove = move[moveIdx++];
342 if (animate) {
343 self.animateMove(smove, () => {
344 playSubmove(smove);
345 if (moveIdx < move.length)
346 setTimeout(executeMove, 500);
347 else afterMove(smove, initurn);
348 });
349 } else {
350 playSubmove(smove);
351 if (moveIdx < move.length) executeMove();
352 else afterMove(smove, initurn);
353 }
354 })();
355 };
356 const afterMove = (smove, initurn) => {
357 if (this.vr.turn != initurn) {
358 // Turn has changed: move is complete
359 if (!smove.fen) {
360 // NOTE: only FEN of last sub-move is required (thus setting it here)
361 smove.fen = this.vr.getFen();
362 this.emitFenIfAnalyze();
363 }
364 this.inMultimove = false;
365 const score = this.vr.getCurrentScore();
366 if (score != "*") {
367 const message = getScoreMessage(score);
368 if (!navigate && this.game.mode != "analyze")
369 this.$emit("gameover", score, message);
370 else if (this.game.mode == "analyze")
371 // Just show score on screen (allow undo)
372 this.showEndgameMsg(score + " . " + this.st.tr[message]);
373 }
374 if (!navigate && this.game.mode != "analyze") {
375 const L = this.moves.length;
376 // Post-processing (e.g. computer play)
377 this.$emit("newmove", this.moves[L-1], data);
378 }
379 }
380 };
381 // NOTE: navigate and received are mutually exclusive
382 if (navigate) {
383 // The move to navigate to is necessarily full:
384 if (this.cursor == this.moves.length - 1) return; //no more moves
385 move = this.moves[this.cursor + 1];
386 if (light) {
387 // Just play the move, nothing else:
388 if (!Array.isArray(move)) move = [move];
389 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
390 }
391 else {
392 playMove();
393 this.emitFenIfAnalyze();
394 }
395 this.cursor++;
396 return;
397 }
398 // Forbid playing outside analyze mode, except if move is received.
399 // Sufficient condition because Board already knows which turn it is.
400 if (
401 this.game.mode != "analyze" &&
402 !received &&
403 (this.game.score != "*" || this.cursor < this.moves.length - 1)
404 ) {
405 return;
406 }
407 // To play a received move, cursor must be at the end of the game:
408 if (received && this.cursor < this.moves.length - 1)
409 this.gotoEnd();
410 playMove();
411 },
412 cancelCurrentMultimove: function() {
413 const L = this.moves.length;
414 let move = this.moves[L-1];
415 if (!Array.isArray(move)) move = [move];
416 for (let i=move.length -1; i >= 0; i--) this.vr.undo(move[i]);
417 this.moves.pop();
418 this.cursor--;
419 this.inMultimove = false;
420 },
421 cancelLastMove: function() {
422 // The last played move was canceled (corr game)
423 this.undo();
424 this.moves.pop();
425 },
426 // "light": if gotoMove() or gotoBegin()
427 undo: function(move, light) {
428 if (this.inMultimove) {
429 this.cancelCurrentMultimove();
430 this.incheck = this.vr.getCheckSquares(this.vr.turn);
431 } else {
432 if (!move) {
433 if (this.cursor < 0) return; //no more moves
434 move = this.moves[this.cursor];
435 }
436 // Caution; if multi-move, undo all submoves from last to first
437 undoMove(move, this.vr);
438 if (light) this.cursor--;
439 else {
440 this.positionCursorTo(this.cursor - 1);
441 this.incheck = this.vr.getCheckSquares(this.vr.turn);
442 this.emitFenIfAnalyze();
443 }
444 }
445 },
446 gotoMove: function(index) {
447 if (this.inMultimove) this.cancelCurrentMultimove();
448 if (index == this.cursor) return;
449 if (index < this.cursor) {
450 while (this.cursor > index)
451 this.undo(null, null, "light");
452 }
453 else {
454 // index > this.cursor)
455 while (this.cursor < index)
456 this.play(null, null, "light");
457 }
458 // NOTE: next line also re-assign cursor, but it's very light
459 this.positionCursorTo(index);
460 this.incheck = this.vr.getCheckSquares(this.vr.turn);
461 this.emitFenIfAnalyze();
462 },
463 gotoBegin: function() {
464 if (this.inMultimove) this.cancelCurrentMultimove();
465 while (this.cursor >= 0)
466 this.undo(null, null, "light");
467 if (this.moves.length > 0 && this.moves[0].notation == "...") {
468 this.cursor = 0;
469 this.lastMove = this.moves[0];
470 } else {
471 this.lastMove = null;
472 }
473 this.incheck = [];
474 this.emitFenIfAnalyze();
475 },
476 gotoEnd: function() {
477 if (this.cursor == this.moves.length - 1) return;
478 this.gotoMove(this.moves.length - 1);
479 this.emitFenIfAnalyze();
480 },
481 flip: function() {
482 this.orientation = V.GetOppCol(this.orientation);
483 }
484 }
485 };
486 </script>
487
488 <style lang="sass" scoped>
489 [type="checkbox"]#modalEog+div .card
490 min-height: 45px
491
492 #baseGame
493 width: 100%
494 &:focus
495 outline: none
496
497 #gameContainer
498 margin-left: auto
499 margin-right: auto
500
501 #downloadDiv
502 display: inline-block
503
504 #controls
505 margin: 0 auto
506 text-align: center
507 button
508 display: inline-block
509 width: 20%
510 margin: 0
511
512 #turnIndicator
513 text-align: center
514 font-weight: bold
515
516 #belowControls
517 border-top: 1px solid #2f4f4f
518 text-align: center
519 margin: 0 auto
520 & > #downloadDiv
521 margin: 0
522 & > button
523 margin: 0
524 & > button
525 border-left: 1px solid #2f4f4f
526 margin: 0
527
528 #boardContainer
529 float: left
530 // TODO: later, maybe, allow movesList of variable width
531 // or e.g. between 250 and 350px (but more complicated)
532
533 #movesList
534 width: 280px
535 float: left
536
537 @media screen and (max-width: 767px)
538 #movesList
539 width: 100%
540 float: none
541 clear: both
542 </style>