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