Experimental update: preview corr move + allow deletion of any game
[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 const score = this.vr.getCurrentScore();
372 if (score != "*") {
373 const message = getScoreMessage(score);
374 if (!navigate && this.game.mode != "analyze")
375 this.$emit("gameover", score, message);
376 else if (this.game.mode == "analyze")
377 // Just show score on screen (allow undo)
378 this.showEndgameMsg(score + " . " + this.st.tr[message]);
379 }
380 if (!navigate && this.game.mode != "analyze") {
381 const L = this.moves.length;
382 if (!noemit)
383 // Post-processing (e.g. computer play)
384 this.$emit("newmove", this.moves[L-1]);
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 margin: 0 auto
519 text-align: center
520 display: flex
521 button
522 display: inline-block
523 width: 20%
524 margin: 0
525 padding-top: 5px
526 padding-bottom: 5px
527
528 img.inline
529 height: 24px
530 padding-top: 5px
531 @media screen and (max-width: 767px)
532 height: 18px
533
534 #turnIndicator
535 text-align: center
536 font-weight: bold
537
538 #boardContainer
539 float: left
540 // TODO: later, maybe, allow movesList of variable width
541 // or e.g. between 250 and 350px (but more complicated)
542
543 #movesList
544 width: 280px
545 float: left
546
547 @media screen and (max-width: 767px)
548 #movesList
549 width: 100%
550 float: none
551 clear: both
552 </style>