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