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