Some fixes, wrote some rules, implemented Wormhole variant
[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
9ddaf8da
BA
26 button(@click="gotoBegin()") <<
27 button(@click="undo()") <
71ef1664 28 button(v-if="canFlip" @click="flip()") &#8645;
9ddaf8da
BA
29 button(@click="play()") >
30 button(@click="gotoEnd()") >>
bd76b456 31 #belowControls
20620465 32 #downloadDiv(v-if="allowDownloadPGN")
4f518610 33 a#download(href="#")
9ddaf8da 34 button(@click="download()") {{ st.tr["Download"] }} PGN
6808d7a1 35 button(
20620465 36 v-if="canAnalyze"
6808d7a1
BA
37 @click="analyzePosition()"
38 )
677fe285 39 | {{ st.tr["Analyse"] }}
20620465 40 // NOTE: variants pages already have a "Rules" link on top
6808d7a1
BA
41 button(
42 v-if="!$route.path.match('/variants/')"
43 @click="showRules()"
44 )
4f518610 45 | {{ st.tr["Rules"] }}
cf94b843 46 #movesList
6808d7a1 47 MoveList(
933fd1f9
BA
48 v-if="showMoves != 'none'"
49 :show="showMoves"
6808d7a1
BA
50 :score="game.score"
51 :message="game.scoreMsg"
52 :firstNum="firstMoveNumber"
53 :moves="moves"
54 :cursor="cursor"
55 @goto-move="gotoMove"
56 )
41c80bb6 57 .clearer
a6088c90
BA
58</template>
59
60<script>
61import Board from "@/components/Board.vue";
f21cd6d9 62import MoveList from "@/components/MoveList.vue";
a6088c90
BA
63import { store } from "@/store";
64import { getSquareId } from "@/utils/squareId";
d4036efe 65import { getDate } from "@/utils/datetime";
602d6bef 66import { processModalClick } from "@/utils/modalClick";
77c50966 67import { getScoreMessage } from "@/utils/scoring";
e71161fb
BA
68import { getFullNotation } from "@/utils/notation";
69import { undoMove } from "@/utils/playUndo";
a6088c90 70export default {
6808d7a1 71 name: "my-base-game",
a6088c90
BA
72 components: {
73 Board,
6808d7a1 74 MoveList
a6088c90 75 },
e71161fb 76 props: ["game"],
a6088c90
BA
77 data: function() {
78 return {
79 st: store.state,
b7c32f1a 80 // NOTE: all following variables must be reset at the beginning of a game
e71161fb 81 vr: null, //VariantRules object, game state
a6088c90
BA
82 endgameMessage: "",
83 orientation: "w",
84 score: "*", //'*' means 'unfinished'
b7c32f1a 85 moves: [],
e71161fb 86 // TODO: later, use subCursor to navigate intra-multimoves?
a6088c90
BA
87 cursor: -1, //index of the move just played
88 lastMove: null,
5157ce0b 89 firstMoveNumber: 0, //for printing
e71161fb
BA
90 incheck: [], //for Board
91 inMultimove: false
a6088c90
BA
92 };
93 },
37cdcbf3 94 watch: {
834c202a
BA
95 // game initial FEN changes when a new game starts
96 "game.fenStart": function() {
4b0384fa 97 this.re_setVariables();
37cdcbf3
BA
98 },
99 },
a6088c90
BA
100 computed: {
101 showMoves: function() {
933fd1f9
BA
102 return this.game.score != "*"
103 ? "all"
104 : (this.vr ? this.vr.showMoves : "none");
20620465
BA
105 },
106 showTurn: function() {
71ef1664
BA
107 return (
108 this.game.score == '*' &&
109 this.vr &&
110 (this.vr.showMoves != "all" || !this.vr.canFlip)
111 );
a6088c90 112 },
58ae6be5 113 turn: function() {
71ef1664
BA
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!"]
a13cbc0f 121 : "";
58ae6be5 122 },
20620465 123 canAnalyze: function() {
933fd1f9 124 return this.game.mode != "analyze" && this.vr && this.vr.canAnalyze;
20620465 125 },
71ef1664
BA
126 canFlip: function() {
127 return this.vr && this.vr.canFlip;
128 },
20620465 129 allowDownloadPGN: function() {
933fd1f9 130 return this.game.score != "*" || (this.vr && this.vr.showMoves == "all");
6808d7a1 131 }
a6088c90 132 },
4b0384fa 133 created: function() {
6808d7a1 134 if (this.game.fenStart) this.re_setVariables();
4b0384fa 135 },
cf94b843 136 mounted: function() {
e71161fb
BA
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 }
5b3dc10e
BA
145 document.getElementById("eogDiv").addEventListener(
146 "click",
147 processModalClick);
cf94b843 148 },
a6088c90 149 methods: {
9ca1e26b 150 focusBg: function() {
9ca1e26b
BA
151 document.getElementById("baseGame").focus();
152 },
153 handleKeys: function(e) {
6808d7a1
BA
154 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
155 switch (e.keyCode) {
9ca1e26b
BA
156 case 37:
157 this.undo();
158 break;
159 case 39:
160 this.play();
161 break;
5701c228 162 case 38:
9ca1e26b
BA
163 this.gotoBegin();
164 break;
165 case 40:
166 this.gotoEnd();
167 break;
168 case 32:
9ca1e26b
BA
169 this.flip();
170 break;
171 }
172 },
dcd68c41 173 handleScroll: function(e) {
e71161fb
BA
174 e.preventDefault();
175 if (e.deltaY < 0) this.undo();
176 else if (e.deltaY > 0) this.play();
dcd68c41 177 },
0e16cb26
BA
178 showRules: function() {
179 //this.$router.push("/variants/" + this.game.vname);
180 window.open("#/variants/" + this.game.vname, "_blank"); //better
181 },
4b0384fa
BA
182 re_setVariables: function() {
183 this.endgameMessage = "";
8477e53d
BA
184 // "w": default orientation for observed games
185 this.orientation = this.game.mycolor || "w";
4b0384fa 186 this.moves = JSON.parse(JSON.stringify(this.game.moves || []));
e71161fb
BA
187 // Post-processing: decorate each move with notation and FEN
188 this.vr = new V(this.game.fenStart);
8477e53d
BA
189 const parsedFen = V.ParseFen(this.game.fenStart);
190 const firstMoveColor = parsedFen.turn;
191 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2);
d4036efe 192 this.moves.forEach(move => {
e71161fb
BA
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 });
d4036efe 199 });
8477e53d 200 if (firstMoveColor == "b") {
311cba76 201 // 'start' & 'end' is required for Board component
6808d7a1 202 this.moves.unshift({
6808d7a1 203 notation: "...",
311cba76 204 start: { x: -1, y: -1 },
6808d7a1
BA
205 end: { x: -1, y: -1 }
206 });
697ee580 207 }
e71161fb 208 this.positionCursorTo(this.moves.length - 1);
9ef63965 209 this.incheck = this.vr.getCheckSquares(this.vr.turn);
4b0384fa 210 },
e71161fb
BA
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 },
63ca2b89 225 analyzePosition: function() {
6808d7a1
BA
226 const newUrl =
227 "/analyse/" +
228 this.game.vname +
229 "/?fen=" +
230 this.vr.getFen().replace(/ /g, "_");
910d631b 231 // Open in same tab in live games (against cheating)
6808d7a1 232 if (this.game.type == "live") this.$router.push(newUrl);
910d631b 233 else window.open("#" + newUrl);
603b8a8b 234 },
a6088c90
BA
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");
6808d7a1
BA
240 downloadAnchor.href =
241 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
a6088c90
BA
242 downloadAnchor.click();
243 },
244 getPgn: function() {
245 let pgn = "";
246 pgn += '[Site "vchess.club"]\n';
834c202a 247 pgn += '[Variant "' + this.game.vname + '"]\n';
a6088c90 248 pgn += '[Date "' + getDate(new Date()) + '"]\n';
d4036efe
BA
249 pgn += '[White "' + this.game.players[0].name + '"]\n';
250 pgn += '[Black "' + this.game.players[1].name + '"]\n';
834c202a 251 pgn += '[Fen "' + this.game.fenStart + '"]\n';
430a2038 252 pgn += '[Result "' + this.game.score + '"]\n\n';
e71161fb
BA
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]) + " ";
a6088c90
BA
257 }
258 return pgn + "\n";
259 },
b988c726
BA
260 showEndgameMsg: function(message) {
261 this.endgameMessage = message;
4494c17c 262 let modalBox = document.getElementById("modalEog");
a6088c90 263 modalBox.checked = true;
6808d7a1
BA
264 setTimeout(() => {
265 modalBox.checked = false;
266 }, 2000);
a6088c90 267 },
e71161fb 268 // Animate an elementary move
63ca2b89 269 animateMove: function(move, callback) {
a6088c90
BA
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();
6808d7a1
BA
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 );
a6088c90
BA
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");
6808d7a1 284 for (let i = 0; i < squares.length; i++) {
a6088c90 285 let square = squares.item(i);
6808d7a1 286 if (square.id != getSquareId(move.start)) square.style.zIndex = "-1";
a6088c90 287 }
6808d7a1
BA
288 movingPiece.style.transform =
289 "translate(" + translation.x + "px," + translation.y + "px)";
910d631b 290 movingPiece.style.transitionDuration = "0.25s";
a6088c90 291 movingPiece.style.zIndex = "3000";
6808d7a1
BA
292 setTimeout(() => {
293 for (let i = 0; i < squares.length; i++)
a6088c90
BA
294 squares.item(i).style.zIndex = "auto";
295 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
63ca2b89 296 callback();
a6088c90
BA
297 }, 250);
298 },
e71161fb
BA
299 // "light": if gotoMove() or gotoEnd()
300 // data: some custom data (addTime) to be re-emitted
301 play: function(move, received, light, data) {
9d54ab89 302 const navigate = !move;
e71161fb
BA
303 const playSubmove = (smove) => {
304 if (!navigate) smove.notation = this.vr.getNotation(smove);
305 this.vr.play(smove);
306 this.lastMove = smove;
307 // Is opponent in check?
308 this.incheck = this.vr.getCheckSquares(this.vr.turn);
309 if (!navigate) {
310 if (!this.inMultimove) {
311 if (this.cursor < this.moves.length - 1)
312 this.moves = this.moves.slice(0, Math.max(this.cursor, 0));
313 this.moves.push(smove);
314 this.inMultimove = true; //potentially
315 this.cursor++;
316 } else {
317 // Already in the middle of a multi-move
318 const L = this.moves.length;
319 if (!Array.isArray(this.moves[L-1]))
320 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
321 else
322 this.$set(this.moves, L-1, this.moves.concat([smove]));
323 }
324 }
325 };
326 const playMove = () => {
327 const animate = V.ShowMoves == "all" && received;
328 if (!Array.isArray(move)) move = [move];
329 let moveIdx = 0;
330 let self = this;
331 const initurn = this.vr.turn;
332 (function executeMove() {
333 const smove = move[moveIdx++];
334 if (animate) {
335 self.animateMove(smove, () => {
336 playSubmove(smove);
337 if (moveIdx < move.length)
338 setTimeout(executeMove, 500);
339 else afterMove(smove, initurn);
340 });
341 } else {
342 playSubmove(smove);
343 if (moveIdx < move.length) executeMove();
344 else afterMove(smove, initurn);
345 }
346 })();
347 };
348 const afterMove = (smove, initurn) => {
349 if (this.st.settings.sound == 2)
350 new Audio("/sounds/move.mp3").play().catch(() => {});
351 if (this.vr.turn != initurn) {
352 // Turn has changed: move is complete
353 this.inMultimove = false;
354 const score = this.vr.getCurrentScore();
355 if (score != "*") {
356 const message = getScoreMessage(score);
357 if (!navigate && this.game.mode != "analyze")
358 this.$emit("gameover", score, message);
359 // Just show score on screen (allow undo)
311cba76 360 else this.showEndgameMsg(score + " . " + this.st.tr[message]);
e71161fb
BA
361 }
362 if (!navigate && this.game.mode != "analyze") {
363 const L = this.moves.length;
364 // Post-processing (e.g. computer play)
365 this.$emit("newmove", this.moves[L-1], data);
366 }
367 }
368 };
369 // NOTE: navigate and received are mutually exclusive
370 if (navigate) {
371 // The move to navigate to is necessarily full:
372 if (this.cursor == this.moves.length - 1) return; //no more moves
373 move = this.moves[this.cursor + 1];
374 if (light) {
375 // Just play the move, nothing else:
376 if (!Array.isArray(move)) move = [move];
377 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
378 }
379 else playMove();
380 this.cursor++;
381 return;
382 }
63ca2b89
BA
383 // Forbid playing outside analyze mode, except if move is received.
384 // Sufficient condition because Board already knows which turn it is.
6808d7a1 385 if (
6808d7a1 386 this.game.mode != "analyze" &&
e71161fb 387 !received &&
6808d7a1
BA
388 (this.game.score != "*" || this.cursor < this.moves.length - 1)
389 ) {
a6088c90
BA
390 return;
391 }
e71161fb
BA
392 // To play a received move, cursor must be at the end of the game:
393 if (received && this.cursor < this.moves.length - 1)
394 this.gotoEnd();
395 playMove();
396 },
397 cancelCurrentMultimove: function() {
398 // Cancel current multi-move
399 const L = this.moves.length;
400 let move = this.moves[L-1];
401 if (!Array.isArray(move)) move = [move];
402 for (let i=move.length -1; i >= 0; i--) this.vr.undo(move[i]);
403 this.moves.pop();
404 this.cursor--;
405 this.inMultimove = false;
406 },
407 cancelLastMove: function() {
408 // The last played move was canceled (corr game)
409 this.undo();
410 this.moves.pop();
411 },
412 // "light": if gotoMove() or gotoBegin()
413 undo: function(move, light) {
414 if (this.inMultimove) {
415 this.cancelCurrentMultimove();
63ca2b89 416 this.incheck = this.vr.getCheckSquares(this.vr.turn);
e71161fb
BA
417 } else {
418 if (!move) {
419 if (this.cursor < 0) return; //no more moves
420 move = this.moves[this.cursor];
421 }
422 // Caution; if multi-move, undo all submoves from last to first
423 undoMove(move, this.vr);
424 if (light) this.cursor--;
425 else {
426 this.positionCursorTo(this.cursor - 1);
427 if (this.st.settings.sound == 2)
428 new Audio("/sounds/undo.mp3").play().catch(() => {});
429 this.incheck = this.vr.getCheckSquares(this.vr.turn);
63ca2b89 430 }
a6088c90 431 }
a6088c90
BA
432 },
433 gotoMove: function(index) {
e71161fb
BA
434 if (this.inMultimove) this.cancelCurrentMultimove();
435 if (index == this.cursor) return;
436 if (index < this.cursor) {
437 while (this.cursor > index)
438 this.undo(null, null, "light");
439 }
440 else {
441 // index > this.cursor)
442 while (this.cursor < index)
443 this.play(null, null, "light");
444 }
445 // NOTE: next line also re-assign cursor, but it's very light
446 this.positionCursorTo(index);
8b405c81 447 this.incheck = this.vr.getCheckSquares(this.vr.turn);
a6088c90
BA
448 },
449 gotoBegin: function() {
e71161fb
BA
450 if (this.inMultimove) this.cancelCurrentMultimove();
451 while (this.cursor >= 0)
452 this.undo(null, null, "light");
6808d7a1 453 if (this.moves.length > 0 && this.moves[0].notation == "...") {
5701c228
BA
454 this.cursor = 0;
455 this.lastMove = this.moves[0];
6808d7a1 456 } else {
5701c228
BA
457 this.lastMove = null;
458 }
e71161fb 459 this.incheck = [];
a6088c90
BA
460 },
461 gotoEnd: function() {
6808d7a1
BA
462 if (this.cursor == this.moves.length - 1) return;
463 this.gotoMove(this.moves.length - 1);
a6088c90
BA
464 },
465 flip: function() {
0e16cb26 466 this.orientation = V.GetOppCol(this.orientation);
6808d7a1
BA
467 }
468 }
a6088c90
BA
469};
470</script>
72ccbd67 471
41c80bb6 472<style lang="sass" scoped>
9a3049f3
BA
473[type="checkbox"]#modalEog+div .card
474 min-height: 45px
910d631b 475
cf94b843
BA
476#baseGame
477 width: 100%
4f518610
BA
478 &:focus
479 outline: none
cf94b843
BA
480
481#gameContainer
72ccbd67
BA
482 margin-left: auto
483 margin-right: auto
cf94b843 484
ed06d9e9
BA
485#downloadDiv
486 display: inline-block
487
72ccbd67 488#controls
bd76b456 489 margin: 0 auto
71ef1664 490 text-align: center
72ccbd67
BA
491 button
492 display: inline-block
493 width: 20%
494 margin: 0
910d631b 495
0e16cb26
BA
496#turnIndicator
497 text-align: center
29bc61be 498 font-weight: bold
910d631b 499
bd76b456
BA
500#belowControls
501 border-top: 1px solid #2f4f4f
cf94b843 502 text-align: center
bd76b456
BA
503 margin: 0 auto
504 & > #downloadDiv
505 margin: 0
506 & > button
507 margin: 0
508 & > button
509 border-left: 1px solid #2f4f4f
510 margin: 0
910d631b 511
72ccbd67 512#boardContainer
cf94b843 513 float: left
41c80bb6
BA
514// TODO: later, maybe, allow movesList of variable width
515// or e.g. between 250 and 350px (but more complicated)
910d631b 516
cf94b843
BA
517#movesList
518 width: 280px
519 float: left
910d631b 520
96e9585a
BA
521@media screen and (max-width: 767px)
522 #movesList
523 width: 100%
524 float: none
525 clear: both
72ccbd67 526</style>