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