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