Debug Knightrelay variant
[vchess.git] / client / src / components / BaseGame.vue
CommitLineData
a6088c90 1<template lang="pug">
6808d7a1
BA
2div#baseGame(
3 tabindex=-1
4 @click="focusBg()"
5 @keydown="handleKeys($event)"
6 @wheel="handleScroll($event)"
7)
7e355d68 8 input#modalEog.modal(type="checkbox")
6808d7a1
BA
9 div#eogDiv(
10 role="dialog"
11 data-checkbox="modalEog"
12 )
9a3049f3 13 .card.text-center
7e355d68 14 label.modal-close(for="modalEog")
9a3049f3 15 h3.section {{ endgameMessage }}
602d6bef 16 input#modalAdjust.modal(type="checkbox")
6808d7a1
BA
17 div#adjuster(
18 role="dialog"
19 data-checkbox="modalAdjust"
20 )
9a3049f3 21 .card.text-center
602d6bef 22 label.modal-close(for="modalAdjust")
9a3049f3 23 label(for="boardSize") {{ st.tr["Board size"] }}
6808d7a1
BA
24 input#boardSize.slider(
25 type="range"
26 min="0"
27 max="100"
28 value="50"
29 @input="adjustBoard()"
30 )
cf94b843
BA
31 #gameContainer
32 #boardContainer
6808d7a1
BA
33 Board(
34 :vr="vr"
35 :last-move="lastMove"
20620465
BA
36 :analyze="game.mode=='analyze'"
37 :score="game.score"
6808d7a1
BA
38 :user-color="game.mycolor"
39 :orientation="orientation"
40 :vname="game.vname"
41 :incheck="incheck"
42 @play-move="play"
43 )
20620465 44 #turnIndicator(v-if="showTurn") {{ turn }}
cf94b843 45 #controls
9ddaf8da
BA
46 button(@click="gotoBegin()") <<
47 button(@click="undo()") <
71ef1664 48 button(v-if="canFlip" @click="flip()") &#8645;
9ddaf8da
BA
49 button(@click="play()") >
50 button(@click="gotoEnd()") >>
bd76b456 51 #belowControls
20620465 52 #downloadDiv(v-if="allowDownloadPGN")
4f518610 53 a#download(href="#")
9ddaf8da 54 button(@click="download()") {{ st.tr["Download"] }} PGN
910d631b 55 button(onClick="window.doClick('modalAdjust')") &#10530;
6808d7a1 56 button(
20620465 57 v-if="canAnalyze"
6808d7a1
BA
58 @click="analyzePosition()"
59 )
677fe285 60 | {{ st.tr["Analyse"] }}
20620465 61 // NOTE: variants pages already have a "Rules" link on top
6808d7a1
BA
62 button(
63 v-if="!$route.path.match('/variants/')"
64 @click="showRules()"
65 )
4f518610 66 | {{ st.tr["Rules"] }}
cf94b843 67 #movesList
6808d7a1 68 MoveList(
933fd1f9
BA
69 v-if="showMoves != 'none'"
70 :show="showMoves"
6808d7a1
BA
71 :score="game.score"
72 :message="game.scoreMsg"
73 :firstNum="firstMoveNumber"
74 :moves="moves"
75 :cursor="cursor"
76 @goto-move="gotoMove"
77 )
41c80bb6 78 .clearer
a6088c90
BA
79</template>
80
81<script>
82import Board from "@/components/Board.vue";
f21cd6d9 83import MoveList from "@/components/MoveList.vue";
a6088c90
BA
84import { store } from "@/store";
85import { getSquareId } from "@/utils/squareId";
d4036efe 86import { getDate } from "@/utils/datetime";
602d6bef 87import { processModalClick } from "@/utils/modalClick";
77c50966 88import { getScoreMessage } from "@/utils/scoring";
a6088c90 89export default {
6808d7a1 90 name: "my-base-game",
a6088c90
BA
91 components: {
92 Board,
6808d7a1 93 MoveList
a6088c90 94 },
bc8734ba 95 // "vr": VariantRules object, describing the game state + rules
6808d7a1 96 props: ["vr", "game"],
a6088c90
BA
97 data: function() {
98 return {
99 st: store.state,
b7c32f1a 100 // NOTE: all following variables must be reset at the beginning of a game
a6088c90
BA
101 endgameMessage: "",
102 orientation: "w",
103 score: "*", //'*' means 'unfinished'
b7c32f1a 104 moves: [],
a6088c90
BA
105 cursor: -1, //index of the move just played
106 lastMove: null,
5157ce0b 107 firstMoveNumber: 0, //for printing
a13cbc0f 108 incheck: [] //for Board
a6088c90
BA
109 };
110 },
37cdcbf3 111 watch: {
834c202a
BA
112 // game initial FEN changes when a new game starts
113 "game.fenStart": function() {
4b0384fa 114 this.re_setVariables();
37cdcbf3
BA
115 },
116 },
a6088c90
BA
117 computed: {
118 showMoves: function() {
933fd1f9
BA
119 return this.game.score != "*"
120 ? "all"
121 : (this.vr ? this.vr.showMoves : "none");
20620465
BA
122 },
123 showTurn: function() {
71ef1664
BA
124 return (
125 this.game.score == '*' &&
126 this.vr &&
127 (this.vr.showMoves != "all" || !this.vr.canFlip)
128 );
a6088c90 129 },
58ae6be5 130 turn: function() {
71ef1664
BA
131 if (!this.vr)
132 return "";
133 if (this.vr.showMoves != "all")
134 return this.st.tr[(this.vr.turn == 'w' ? "White" : "Black") + " to move"]
135 // Cannot flip: racing king or circular chess
136 return this.vr.movesCount == 0 && this.game.mycolor == "w"
137 ? this.st.tr["It's your turn!"]
a13cbc0f 138 : "";
58ae6be5 139 },
20620465 140 canAnalyze: function() {
933fd1f9 141 return this.game.mode != "analyze" && this.vr && this.vr.canAnalyze;
20620465 142 },
71ef1664
BA
143 canFlip: function() {
144 return this.vr && this.vr.canFlip;
145 },
20620465 146 allowDownloadPGN: function() {
933fd1f9 147 return this.game.score != "*" || (this.vr && this.vr.showMoves == "all");
6808d7a1 148 }
a6088c90 149 },
4b0384fa 150 created: function() {
6808d7a1 151 if (this.game.fenStart) this.re_setVariables();
4b0384fa 152 },
cf94b843 153 mounted: function() {
6808d7a1
BA
154 [
155 document.getElementById("eogDiv"),
156 document.getElementById("adjuster")
157 ].forEach(elt => elt.addEventListener("click", processModalClick));
96e9585a
BA
158 // Take full width on small screens:
159 let boardSize = parseInt(localStorage.getItem("boardSize"));
6808d7a1
BA
160 if (!boardSize) {
161 boardSize =
162 window.innerWidth >= 768
163 ? 0.75 * Math.min(window.innerWidth, window.innerHeight)
164 : window.innerWidth;
96e9585a 165 }
6808d7a1 166 const movesWidth = window.innerWidth >= 768 ? 280 : 0;
96e9585a
BA
167 document.getElementById("boardContainer").style.width = boardSize + "px";
168 let gameContainer = document.getElementById("gameContainer");
6808d7a1
BA
169 gameContainer.style.width = boardSize + movesWidth + "px";
170 document.getElementById("boardSize").value =
171 (boardSize * 100) / (window.innerWidth - movesWidth);
602d6bef
BA
172 // timeout to avoid calling too many time the adjust method
173 let timeoutLaunched = false;
6808d7a1
BA
174 window.addEventListener("resize", () => {
175 if (!timeoutLaunched) {
602d6bef 176 timeoutLaunched = true;
6808d7a1 177 setTimeout(() => {
602d6bef
BA
178 this.adjustBoard();
179 timeoutLaunched = false;
180 }, 500);
181 }
182 });
cf94b843 183 },
a6088c90 184 methods: {
9ca1e26b 185 focusBg: function() {
9ca1e26b
BA
186 document.getElementById("baseGame").focus();
187 },
602d6bef
BA
188 adjustBoard: function() {
189 const boardContainer = document.getElementById("boardContainer");
6808d7a1 190 if (!boardContainer) return; //no board on page
602d6bef 191 const k = document.getElementById("boardSize").value;
6808d7a1 192 const movesWidth = window.innerWidth >= 768 ? 280 : 0;
602d6bef
BA
193 const minBoardWidth = 240; //TODO: these 240 and 280 are arbitrary...
194 // Value of 0 is board min size; 100 is window.width [- movesWidth]
6808d7a1
BA
195 const boardSize =
196 minBoardWidth +
197 (k * (window.innerWidth - (movesWidth + minBoardWidth))) / 100;
602d6bef
BA
198 localStorage.setItem("boardSize", boardSize);
199 boardContainer.style.width = boardSize + "px";
200 document.getElementById("gameContainer").style.width =
6808d7a1 201 boardSize + movesWidth + "px";
602d6bef 202 },
9ca1e26b 203 handleKeys: function(e) {
6808d7a1
BA
204 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
205 switch (e.keyCode) {
9ca1e26b
BA
206 case 37:
207 this.undo();
208 break;
209 case 39:
210 this.play();
211 break;
5701c228 212 case 38:
9ca1e26b
BA
213 this.gotoBegin();
214 break;
215 case 40:
216 this.gotoEnd();
217 break;
218 case 32:
9ca1e26b
BA
219 this.flip();
220 break;
221 }
222 },
dcd68c41 223 handleScroll: function(e) {
4f518610 224 // NOTE: since game.mode=="analyze" => no score, next condition is enough
6808d7a1 225 if (this.game.score != "*") {
41c80bb6 226 e.preventDefault();
6808d7a1
BA
227 if (e.deltaY < 0) this.undo();
228 else if (e.deltaY > 0) this.play();
41c80bb6 229 }
dcd68c41 230 },
0e16cb26
BA
231 showRules: function() {
232 //this.$router.push("/variants/" + this.game.vname);
233 window.open("#/variants/" + this.game.vname, "_blank"); //better
234 },
4b0384fa
BA
235 re_setVariables: function() {
236 this.endgameMessage = "";
8477e53d
BA
237 // "w": default orientation for observed games
238 this.orientation = this.game.mycolor || "w";
4b0384fa 239 this.moves = JSON.parse(JSON.stringify(this.game.moves || []));
8477e53d
BA
240 // Post-processing: decorate each move with color, notation and FEN
241 let vr_tmp = new V(this.game.fenStart);
242 const parsedFen = V.ParseFen(this.game.fenStart);
243 const firstMoveColor = parsedFen.turn;
244 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2);
d4036efe 245 this.moves.forEach(move => {
27d18a24
BA
246 move.color = vr_tmp.turn;
247 move.notation = vr_tmp.getNotation(move);
248 vr_tmp.play(move);
249 move.fen = vr_tmp.getFen();
d4036efe 250 });
8477e53d 251 if (firstMoveColor == "b") {
697ee580 252 // 'end' is required for Board component to check lastMove for e.p.
6808d7a1
BA
253 this.moves.unshift({
254 color: "w",
255 notation: "...",
256 end: { x: -1, y: -1 }
257 });
697ee580 258 }
4b0384fa 259 const L = this.moves.length;
6808d7a1
BA
260 this.cursor = L - 1;
261 this.lastMove = L > 0 ? this.moves[L - 1] : null;
9ef63965 262 this.incheck = this.vr.getCheckSquares(this.vr.turn);
4b0384fa 263 },
63ca2b89 264 analyzePosition: function() {
6808d7a1
BA
265 const newUrl =
266 "/analyse/" +
267 this.game.vname +
268 "/?fen=" +
269 this.vr.getFen().replace(/ /g, "_");
910d631b 270 // Open in same tab in live games (against cheating)
6808d7a1 271 if (this.game.type == "live") this.$router.push(newUrl);
910d631b 272 else window.open("#" + newUrl);
603b8a8b 273 },
a6088c90
BA
274 download: function() {
275 const content = this.getPgn();
276 // Prepare and trigger download link
277 let downloadAnchor = document.getElementById("download");
278 downloadAnchor.setAttribute("download", "game.pgn");
6808d7a1
BA
279 downloadAnchor.href =
280 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
a6088c90
BA
281 downloadAnchor.click();
282 },
283 getPgn: function() {
284 let pgn = "";
285 pgn += '[Site "vchess.club"]\n';
834c202a 286 pgn += '[Variant "' + this.game.vname + '"]\n';
a6088c90 287 pgn += '[Date "' + getDate(new Date()) + '"]\n';
d4036efe
BA
288 pgn += '[White "' + this.game.players[0].name + '"]\n';
289 pgn += '[Black "' + this.game.players[1].name + '"]\n';
834c202a 290 pgn += '[Fen "' + this.game.fenStart + '"]\n';
430a2038 291 pgn += '[Result "' + this.game.score + '"]\n\n';
a6088c90
BA
292 let counter = 1;
293 let i = 0;
6808d7a1
BA
294 while (i < this.moves.length) {
295 pgn += counter++ + ".";
296 for (let color of ["w", "b"]) {
a6088c90
BA
297 let move = "";
298 while (i < this.moves.length && this.moves[i].color == color)
d4036efe 299 move += this.moves[i++].notation + ",";
6808d7a1 300 move = move.slice(0, -1); //remove last comma
d4036efe 301 pgn += move + (i < this.moves.length ? " " : "");
a6088c90
BA
302 }
303 }
304 return pgn + "\n";
305 },
b988c726
BA
306 showEndgameMsg: function(message) {
307 this.endgameMessage = message;
4494c17c 308 let modalBox = document.getElementById("modalEog");
a6088c90 309 modalBox.checked = true;
6808d7a1
BA
310 setTimeout(() => {
311 modalBox.checked = false;
312 }, 2000);
a6088c90 313 },
63ca2b89 314 animateMove: function(move, callback) {
a6088c90
BA
315 let startSquare = document.getElementById(getSquareId(move.start));
316 let endSquare = document.getElementById(getSquareId(move.end));
317 let rectStart = startSquare.getBoundingClientRect();
318 let rectEnd = endSquare.getBoundingClientRect();
6808d7a1
BA
319 let translation = {
320 x: rectEnd.x - rectStart.x,
321 y: rectEnd.y - rectStart.y
322 };
323 let movingPiece = document.querySelector(
324 "#" + getSquareId(move.start) + " > img.piece"
325 );
a6088c90
BA
326 // HACK for animation (with positive translate, image slides "under background")
327 // Possible improvement: just alter squares on the piece's way...
328 const squares = document.getElementsByClassName("board");
6808d7a1 329 for (let i = 0; i < squares.length; i++) {
a6088c90 330 let square = squares.item(i);
6808d7a1 331 if (square.id != getSquareId(move.start)) square.style.zIndex = "-1";
a6088c90 332 }
6808d7a1
BA
333 movingPiece.style.transform =
334 "translate(" + translation.x + "px," + translation.y + "px)";
910d631b 335 movingPiece.style.transitionDuration = "0.25s";
a6088c90 336 movingPiece.style.zIndex = "3000";
6808d7a1
BA
337 setTimeout(() => {
338 for (let i = 0; i < squares.length; i++)
a6088c90
BA
339 squares.item(i).style.zIndex = "auto";
340 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
63ca2b89 341 callback();
a6088c90
BA
342 }, 250);
343 },
63ca2b89
BA
344 play: function(move, receive) {
345 // NOTE: navigate and receive are mutually exclusive
9d54ab89 346 const navigate = !move;
63ca2b89
BA
347 // Forbid playing outside analyze mode, except if move is received.
348 // Sufficient condition because Board already knows which turn it is.
6808d7a1
BA
349 if (
350 !navigate &&
351 this.game.mode != "analyze" &&
352 !receive &&
353 (this.game.score != "*" || this.cursor < this.moves.length - 1)
354 ) {
a6088c90
BA
355 return;
356 }
63ca2b89 357 const doPlayMove = () => {
910d631b
BA
358 // To play a move, cursor must be at the end of the game:
359 if (!!receive && this.cursor < this.moves.length - 1) this.gotoEnd();
6808d7a1
BA
360 if (navigate) {
361 if (this.cursor == this.moves.length - 1) return; //no more moves
362 move = this.moves[this.cursor + 1];
363 } else {
63ca2b89
BA
364 move.color = this.vr.turn;
365 move.notation = this.vr.getNotation(move);
366 }
367 this.vr.play(move);
368 this.cursor++;
369 this.lastMove = move;
370 if (this.st.settings.sound == 2)
6808d7a1
BA
371 new Audio("/sounds/move.mp3").play().catch(() => {});
372 if (!navigate) {
63ca2b89 373 move.fen = this.vr.getFen();
9d54ab89 374 // Stack move on movesList at current cursor
6808d7a1
BA
375 if (this.cursor == this.moves.length) this.moves.push(move);
376 else this.moves = this.moves.slice(0, this.cursor).concat([move]);
9d54ab89 377 }
63ca2b89
BA
378 // Is opponent in check?
379 this.incheck = this.vr.getCheckSquares(this.vr.turn);
380 const score = this.vr.getCurrentScore();
6808d7a1 381 if (score != "*") {
77c50966 382 const message = getScoreMessage(score);
63ca2b89
BA
383 if (this.game.mode != "analyze")
384 this.$emit("gameover", score, message);
6808d7a1
BA
385 //just show score on screen (allow undo)
386 else this.showEndgameMsg(score + " . " + message);
63ca2b89 387 }
6808d7a1 388 if (!navigate && this.game.mode != "analyze")
4f518610 389 this.$emit("newmove", move); //post-processing (e.g. computer play)
63ca2b89 390 };
20620465 391 if (!!receive && V.ShowMoves == "all")
63ca2b89 392 this.animateMove(move, doPlayMove);
6808d7a1 393 else doPlayMove();
a6088c90
BA
394 },
395 undo: function(move) {
9d54ab89 396 const navigate = !move;
6808d7a1
BA
397 if (navigate) {
398 if (this.cursor < 0) return; //no more moves
a6088c90
BA
399 move = this.moves[this.cursor];
400 }
401 this.vr.undo(move);
402 this.cursor--;
6808d7a1 403 this.lastMove = this.cursor >= 0 ? this.moves[this.cursor] : undefined;
a6088c90 404 if (this.st.settings.sound == 2)
6808d7a1 405 new Audio("/sounds/undo.mp3").play().catch(() => {});
a6088c90 406 this.incheck = this.vr.getCheckSquares(this.vr.turn);
6808d7a1 407 if (!navigate) this.moves.pop();
a6088c90
BA
408 },
409 gotoMove: function(index) {
37cdcbf3 410 this.vr.re_init(this.moves[index].fen);
a6088c90
BA
411 this.cursor = index;
412 this.lastMove = this.moves[index];
8b405c81 413 this.incheck = this.vr.getCheckSquares(this.vr.turn);
a6088c90
BA
414 },
415 gotoBegin: function() {
6808d7a1 416 if (this.cursor == -1) return;
834c202a 417 this.vr.re_init(this.game.fenStart);
6808d7a1 418 if (this.moves.length > 0 && this.moves[0].notation == "...") {
5701c228
BA
419 this.cursor = 0;
420 this.lastMove = this.moves[0];
6808d7a1 421 } else {
5701c228
BA
422 this.cursor = -1;
423 this.lastMove = null;
424 }
8b405c81 425 this.incheck = this.vr.getCheckSquares(this.vr.turn);
a6088c90
BA
426 },
427 gotoEnd: function() {
6808d7a1
BA
428 if (this.cursor == this.moves.length - 1) return;
429 this.gotoMove(this.moves.length - 1);
a6088c90
BA
430 },
431 flip: function() {
0e16cb26 432 this.orientation = V.GetOppCol(this.orientation);
6808d7a1
BA
433 }
434 }
a6088c90
BA
435};
436</script>
72ccbd67 437
41c80bb6 438<style lang="sass" scoped>
9a3049f3
BA
439[type="checkbox"]#modalEog+div .card
440 min-height: 45px
910d631b 441
9a3049f3
BA
442[type="checkbox"]#modalAdjust+div .card
443 padding: 5px
444
cf94b843
BA
445#baseGame
446 width: 100%
4f518610
BA
447 &:focus
448 outline: none
cf94b843
BA
449
450#gameContainer
72ccbd67
BA
451 margin-left: auto
452 margin-right: auto
cf94b843 453
ed06d9e9
BA
454#downloadDiv
455 display: inline-block
456
72ccbd67 457#controls
bd76b456 458 margin: 0 auto
71ef1664 459 text-align: center
72ccbd67
BA
460 button
461 display: inline-block
462 width: 20%
463 margin: 0
910d631b 464
0e16cb26
BA
465#turnIndicator
466 text-align: center
29bc61be 467 font-weight: bold
910d631b 468
bd76b456
BA
469#belowControls
470 border-top: 1px solid #2f4f4f
cf94b843 471 text-align: center
bd76b456
BA
472 margin: 0 auto
473 & > #downloadDiv
474 margin: 0
475 & > button
476 margin: 0
477 & > button
478 border-left: 1px solid #2f4f4f
479 margin: 0
910d631b 480
72ccbd67 481#boardContainer
cf94b843 482 float: left
41c80bb6
BA
483// TODO: later, maybe, allow movesList of variable width
484// or e.g. between 250 and 350px (but more complicated)
910d631b 485
cf94b843
BA
486#movesList
487 width: 280px
488 float: left
910d631b 489
96e9585a
BA
490@media screen and (max-width: 767px)
491 #movesList
492 width: 100%
493 float: none
494 clear: both
72ccbd67 495</style>