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