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