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