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