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