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