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