Experimental update: preview corr move + allow deletion of any game
[vchess.git] / client / src / components / BaseGame.vue
CommitLineData
a6088c90 1<template lang="pug">
e71161fb 2div#baseGame
7e355d68 3 input#modalEog.modal(type="checkbox")
6808d7a1
BA
4 div#eogDiv(
5 role="dialog"
6 data-checkbox="modalEog"
7 )
9a3049f3 8 .card.text-center
7e355d68 9 label.modal-close(for="modalEog")
9a3049f3 10 h3.section {{ endgameMessage }}
cf94b843
BA
11 #gameContainer
12 #boardContainer
6808d7a1
BA
13 Board(
14 :vr="vr"
15 :last-move="lastMove"
20620465
BA
16 :analyze="game.mode=='analyze'"
17 :score="game.score"
6808d7a1
BA
18 :user-color="game.mycolor"
19 :orientation="orientation"
20 :vname="game.vname"
21 :incheck="incheck"
22 @play-move="play"
23 )
20620465 24 #turnIndicator(v-if="showTurn") {{ turn }}
cf94b843 25 #controls
b9a5fe01
BA
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")
cf94b843 36 #movesList
6808d7a1 37 MoveList(
933fd1f9 38 :show="showMoves"
feaf1bf7
BA
39 :canAnalyze="canAnalyze"
40 :canDownload="allowDownloadPGN"
6808d7a1
BA
41 :score="game.score"
42 :message="game.scoreMsg"
43 :firstNum="firstMoveNumber"
44 :moves="moves"
45 :cursor="cursor"
feaf1bf7
BA
46 @download="download"
47 @showrules="showRules"
48 @analyze="analyzePosition"
6808d7a1
BA
49 @goto-move="gotoMove"
50 )
41c80bb6 51 .clearer
a6088c90
BA
52</template>
53
54<script>
55import Board from "@/components/Board.vue";
f21cd6d9 56import MoveList from "@/components/MoveList.vue";
a6088c90
BA
57import { store } from "@/store";
58import { getSquareId } from "@/utils/squareId";
d4036efe 59import { getDate } from "@/utils/datetime";
602d6bef 60import { processModalClick } from "@/utils/modalClick";
77c50966 61import { getScoreMessage } from "@/utils/scoring";
e71161fb
BA
62import { getFullNotation } from "@/utils/notation";
63import { undoMove } from "@/utils/playUndo";
a6088c90 64export default {
6808d7a1 65 name: "my-base-game",
a6088c90
BA
66 components: {
67 Board,
6808d7a1 68 MoveList
a6088c90 69 },
e71161fb 70 props: ["game"],
a6088c90
BA
71 data: function() {
72 return {
73 st: store.state,
b7c32f1a 74 // NOTE: all following variables must be reset at the beginning of a game
e71161fb 75 vr: null, //VariantRules object, game state
a6088c90
BA
76 endgameMessage: "",
77 orientation: "w",
78 score: "*", //'*' means 'unfinished'
b7c32f1a 79 moves: [],
a6088c90
BA
80 cursor: -1, //index of the move just played
81 lastMove: null,
5157ce0b 82 firstMoveNumber: 0, //for printing
e71161fb 83 incheck: [], //for Board
57eb158f
BA
84 inMultimove: false,
85 inPlay: false,
86 stackToPlay: []
a6088c90
BA
87 };
88 },
37cdcbf3 89 watch: {
aae89b49
BA
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();
37cdcbf3
BA
94 },
95 },
a6088c90
BA
96 computed: {
97 showMoves: function() {
933fd1f9
BA
98 return this.game.score != "*"
99 ? "all"
100 : (this.vr ? this.vr.showMoves : "none");
20620465
BA
101 },
102 showTurn: function() {
71ef1664
BA
103 return (
104 this.game.score == '*' &&
105 this.vr &&
106 (this.vr.showMoves != "all" || !this.vr.canFlip)
107 );
a6088c90 108 },
58ae6be5 109 turn: function() {
71ef1664
BA
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!"]
a13cbc0f 117 : "";
58ae6be5 118 },
20620465 119 canAnalyze: function() {
933fd1f9 120 return this.game.mode != "analyze" && this.vr && this.vr.canAnalyze;
20620465 121 },
71ef1664
BA
122 canFlip: function() {
123 return this.vr && this.vr.canFlip;
124 },
20620465 125 allowDownloadPGN: function() {
933fd1f9 126 return this.game.score != "*" || (this.vr && this.vr.showMoves == "all");
6808d7a1 127 }
a6088c90 128 },
4b0384fa 129 created: function() {
6808d7a1 130 if (this.game.fenStart) this.re_setVariables();
4b0384fa 131 },
cf94b843 132 mounted: function() {
e71161fb
BA
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 }
5b3dc10e
BA
141 document.getElementById("eogDiv").addEventListener(
142 "click",
143 processModalClick);
cf94b843 144 },
a6088c90 145 methods: {
9ca1e26b 146 focusBg: function() {
9ca1e26b
BA
147 document.getElementById("baseGame").focus();
148 },
149 handleKeys: function(e) {
6808d7a1
BA
150 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
151 switch (e.keyCode) {
9ca1e26b
BA
152 case 37:
153 this.undo();
154 break;
155 case 39:
156 this.play();
157 break;
5701c228 158 case 38:
9ca1e26b
BA
159 this.gotoBegin();
160 break;
161 case 40:
162 this.gotoEnd();
163 break;
164 case 32:
9ca1e26b
BA
165 this.flip();
166 break;
167 }
168 },
dcd68c41 169 handleScroll: function(e) {
e71161fb
BA
170 e.preventDefault();
171 if (e.deltaY < 0) this.undo();
172 else if (e.deltaY > 0) this.play();
dcd68c41 173 },
0e16cb26
BA
174 showRules: function() {
175 //this.$router.push("/variants/" + this.game.vname);
176 window.open("#/variants/" + this.game.vname, "_blank"); //better
177 },
4b0384fa
BA
178 re_setVariables: function() {
179 this.endgameMessage = "";
8477e53d
BA
180 // "w": default orientation for observed games
181 this.orientation = this.game.mycolor || "w";
4b0384fa 182 this.moves = JSON.parse(JSON.stringify(this.game.moves || []));
e71161fb
BA
183 // Post-processing: decorate each move with notation and FEN
184 this.vr = new V(this.game.fenStart);
8477e53d
BA
185 const parsedFen = V.ParseFen(this.game.fenStart);
186 const firstMoveColor = parsedFen.turn;
187 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2);
d4036efe 188 this.moves.forEach(move => {
e71161fb
BA
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 });
d4036efe 195 });
8477e53d 196 if (firstMoveColor == "b") {
311cba76 197 // 'start' & 'end' is required for Board component
6808d7a1 198 this.moves.unshift({
6808d7a1 199 notation: "...",
311cba76 200 start: { x: -1, y: -1 },
6808d7a1
BA
201 end: { x: -1, y: -1 }
202 });
697ee580 203 }
e71161fb 204 this.positionCursorTo(this.moves.length - 1);
9ef63965 205 this.incheck = this.vr.getCheckSquares(this.vr.turn);
4b0384fa 206 },
e71161fb
BA
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 },
63ca2b89 221 analyzePosition: function() {
7ba4a5bc 222 let newUrl =
6808d7a1
BA
223 "/analyse/" +
224 this.game.vname +
225 "/?fen=" +
226 this.vr.getFen().replace(/ /g, "_");
7ba4a5bc
BA
227 if (this.game.mycolor)
228 newUrl += "&side=" + this.game.mycolor;
910d631b 229 // Open in same tab in live games (against cheating)
6808d7a1 230 if (this.game.type == "live") this.$router.push(newUrl);
910d631b 231 else window.open("#" + newUrl);
603b8a8b 232 },
a6088c90
BA
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");
6808d7a1
BA
238 downloadAnchor.href =
239 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
a6088c90
BA
240 downloadAnchor.click();
241 },
242 getPgn: function() {
243 let pgn = "";
244 pgn += '[Site "vchess.club"]\n';
834c202a 245 pgn += '[Variant "' + this.game.vname + '"]\n';
a6088c90 246 pgn += '[Date "' + getDate(new Date()) + '"]\n';
d4036efe
BA
247 pgn += '[White "' + this.game.players[0].name + '"]\n';
248 pgn += '[Black "' + this.game.players[1].name + '"]\n';
834c202a 249 pgn += '[Fen "' + this.game.fenStart + '"]\n';
430a2038 250 pgn += '[Result "' + this.game.score + '"]\n\n';
e71161fb
BA
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]) + " ";
a6088c90
BA
255 }
256 return pgn + "\n";
257 },
b988c726
BA
258 showEndgameMsg: function(message) {
259 this.endgameMessage = message;
aae89b49 260 document.getElementById("modalEog").checked = true;
a6088c90 261 },
e71161fb 262 // Animate an elementary move
63ca2b89 263 animateMove: function(move, callback) {
a6088c90 264 let startSquare = document.getElementById(getSquareId(move.start));
f9c36b2d 265 if (!startSquare) return; //shouldn't happen but...
a6088c90
BA
266 let endSquare = document.getElementById(getSquareId(move.end));
267 let rectStart = startSquare.getBoundingClientRect();
268 let rectEnd = endSquare.getBoundingClientRect();
6808d7a1
BA
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 );
efdfb4c7
BA
276 // For some unknown reasons Opera get "movingPiece == null" error
277 // TOOO: is it calling 'animate()' twice ? One extra time ?
278 if (!movingPiece) return;
a6088c90
BA
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");
6808d7a1 282 for (let i = 0; i < squares.length; i++) {
a6088c90 283 let square = squares.item(i);
6808d7a1 284 if (square.id != getSquareId(move.start)) square.style.zIndex = "-1";
a6088c90 285 }
6808d7a1
BA
286 movingPiece.style.transform =
287 "translate(" + translation.x + "px," + translation.y + "px)";
910d631b 288 movingPiece.style.transitionDuration = "0.25s";
a6088c90 289 movingPiece.style.zIndex = "3000";
6808d7a1
BA
290 setTimeout(() => {
291 for (let i = 0; i < squares.length; i++)
a6088c90
BA
292 squares.item(i).style.zIndex = "auto";
293 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
63ca2b89 294 callback();
a6088c90
BA
295 }, 250);
296 },
8055eabd
BA
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 },
e71161fb 306 // "light": if gotoMove() or gotoEnd()
57eb158f
BA
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 }
9d54ab89 316 const navigate = !move;
e71161fb
BA
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)
8055eabd 326 this.moves = this.moves.slice(0, this.cursor + 1);
e71161fb
BA
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 = () => {
7ba4a5bc 341 const animate = V.ShowMoves == "all" && (received || navigate);
e71161fb
BA
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) => {
e71161fb
BA
363 if (this.vr.turn != initurn) {
364 // Turn has changed: move is complete
e891730f 365 if (!smove.fen) {
cc00b83c
BA
366 // NOTE: only FEN of last sub-move is required (thus setting it here)
367 smove.fen = this.vr.getFen();
e891730f
BA
368 this.emitFenIfAnalyze();
369 }
e71161fb
BA
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);
e533e1ba
BA
376 else if (this.game.mode == "analyze")
377 // Just show score on screen (allow undo)
378 this.showEndgameMsg(score + " . " + this.st.tr[message]);
e71161fb
BA
379 }
380 if (!navigate && this.game.mode != "analyze") {
381 const L = this.moves.length;
57eb158f
BA
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 }
e71161fb
BA
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 }
8055eabd
BA
404 else {
405 playMove();
406 this.emitFenIfAnalyze();
407 }
e71161fb
BA
408 this.cursor++;
409 return;
410 }
63ca2b89
BA
411 // Forbid playing outside analyze mode, except if move is received.
412 // Sufficient condition because Board already knows which turn it is.
6808d7a1 413 if (
6808d7a1 414 this.game.mode != "analyze" &&
e71161fb 415 !received &&
6808d7a1
BA
416 (this.game.score != "*" || this.cursor < this.moves.length - 1)
417 ) {
a6088c90
BA
418 return;
419 }
e71161fb
BA
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() {
e71161fb
BA
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();
63ca2b89 443 this.incheck = this.vr.getCheckSquares(this.vr.turn);
e71161fb
BA
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);
e71161fb 454 this.incheck = this.vr.getCheckSquares(this.vr.turn);
8055eabd 455 this.emitFenIfAnalyze();
63ca2b89 456 }
a6088c90 457 }
a6088c90
BA
458 },
459 gotoMove: function(index) {
e71161fb
BA
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);
8b405c81 473 this.incheck = this.vr.getCheckSquares(this.vr.turn);
8055eabd 474 this.emitFenIfAnalyze();
a6088c90
BA
475 },
476 gotoBegin: function() {
e71161fb
BA
477 if (this.inMultimove) this.cancelCurrentMultimove();
478 while (this.cursor >= 0)
479 this.undo(null, null, "light");
6808d7a1 480 if (this.moves.length > 0 && this.moves[0].notation == "...") {
5701c228
BA
481 this.cursor = 0;
482 this.lastMove = this.moves[0];
6808d7a1 483 } else {
5701c228
BA
484 this.lastMove = null;
485 }
e71161fb 486 this.incheck = [];
8055eabd 487 this.emitFenIfAnalyze();
a6088c90
BA
488 },
489 gotoEnd: function() {
6808d7a1
BA
490 if (this.cursor == this.moves.length - 1) return;
491 this.gotoMove(this.moves.length - 1);
8055eabd 492 this.emitFenIfAnalyze();
a6088c90
BA
493 },
494 flip: function() {
0e16cb26 495 this.orientation = V.GetOppCol(this.orientation);
6808d7a1
BA
496 }
497 }
a6088c90
BA
498};
499</script>
72ccbd67 500
41c80bb6 501<style lang="sass" scoped>
9a3049f3
BA
502[type="checkbox"]#modalEog+div .card
503 min-height: 45px
910d631b 504
cf94b843
BA
505#baseGame
506 width: 100%
4f518610
BA
507 &:focus
508 outline: none
cf94b843
BA
509
510#gameContainer
72ccbd67
BA
511 margin-left: auto
512 margin-right: auto
cf94b843 513
ed06d9e9
BA
514#downloadDiv
515 display: inline-block
516
72ccbd67 517#controls
bd76b456 518 margin: 0 auto
71ef1664 519 text-align: center
b9a5fe01 520 display: flex
72ccbd67
BA
521 button
522 display: inline-block
523 width: 20%
524 margin: 0
feaf1bf7
BA
525 padding-top: 5px
526 padding-bottom: 5px
527
528img.inline
529 height: 24px
530 padding-top: 5px
531 @media screen and (max-width: 767px)
532 height: 18px
910d631b 533
0e16cb26
BA
534#turnIndicator
535 text-align: center
29bc61be 536 font-weight: bold
910d631b 537
72ccbd67 538#boardContainer
cf94b843 539 float: left
41c80bb6
BA
540// TODO: later, maybe, allow movesList of variable width
541// or e.g. between 250 and 350px (but more complicated)
910d631b 542
cf94b843
BA
543#movesList
544 width: 280px
545 float: left
910d631b 546
96e9585a
BA
547@media screen and (max-width: 767px)
548 #movesList
549 width: 100%
550 float: none
551 clear: both
72ccbd67 552</style>