3 input#modalEog.modal(type="checkbox")
6 data-checkbox="modalEog"
9 label.modal-close(for="modalEog")
10 h3.section {{ endgameMessage }}
11 input#modalAdjust.modal(type="checkbox")
14 data-checkbox="modalAdjust"
17 label.modal-close(for="modalAdjust")
18 label(for="boardSize") {{ st.tr["Board size"] }}
19 input#boardSize.slider(
24 @input="adjustBoard()"
31 :analyze="game.mode=='analyze'"
33 :user-color="game.mycolor"
34 :orientation="orientation"
39 #turnIndicator(v-if="showTurn") {{ turn }}
41 button(@click="gotoBegin()") <<
42 button(@click="undo()") <
43 button(v-if="canFlip" @click="flip()") ⇅
44 button(@click="play()") >
45 button(@click="gotoEnd()") >>
47 #downloadDiv(v-if="allowDownloadPGN")
49 button(@click="download()") {{ st.tr["Download"] }} PGN
50 button(onClick="window.doClick('modalAdjust')") ⤢
53 @click="analyzePosition()"
55 | {{ st.tr["Analyse"] }}
56 // NOTE: variants pages already have a "Rules" link on top
58 v-if="!$route.path.match('/variants/')"
61 | {{ st.tr["Rules"] }}
64 v-if="showMoves != 'none'"
67 :message="game.scoreMsg"
68 :firstNum="firstMoveNumber"
77 import Board from "@/components/Board.vue";
78 import MoveList from "@/components/MoveList.vue";
79 import { store } from "@/store";
80 import { getSquareId } from "@/utils/squareId";
81 import { getDate } from "@/utils/datetime";
82 import { processModalClick } from "@/utils/modalClick";
83 import { getScoreMessage } from "@/utils/scoring";
84 import { getFullNotation } from "@/utils/notation";
85 import { undoMove } from "@/utils/playUndo";
96 // NOTE: all following variables must be reset at the beginning of a game
97 vr: null, //VariantRules object, game state
100 score: "*", //'*' means 'unfinished'
102 // TODO: later, use subCursor to navigate intra-multimoves?
103 cursor: -1, //index of the move just played
105 firstMoveNumber: 0, //for printing
106 incheck: [], //for Board
111 // game initial FEN changes when a new game starts
112 "game.fenStart": function() {
113 this.re_setVariables();
117 showMoves: function() {
118 return this.game.score != "*"
120 : (this.vr ? this.vr.showMoves : "none");
122 showTurn: function() {
124 this.game.score == '*' &&
126 (this.vr.showMoves != "all" || !this.vr.canFlip)
132 if (this.vr.showMoves != "all")
133 return this.st.tr[(this.vr.turn == 'w' ? "White" : "Black") + " to move"]
134 // Cannot flip: racing king or circular chess
135 return this.vr.movesCount == 0 && this.game.mycolor == "w"
136 ? this.st.tr["It's your turn!"]
139 canAnalyze: function() {
140 return this.game.mode != "analyze" && this.vr && this.vr.canAnalyze;
142 canFlip: function() {
143 return this.vr && this.vr.canFlip;
145 allowDownloadPGN: function() {
146 return this.game.score != "*" || (this.vr && this.vr.showMoves == "all");
149 created: function() {
150 if (this.game.fenStart) this.re_setVariables();
152 mounted: function() {
153 if (!("ontouchstart" in window)) {
155 const baseGameDiv = document.getElementById("baseGame");
156 baseGameDiv.tabIndex = 0;
157 baseGameDiv.addEventListener("click", this.focusBg);
158 baseGameDiv.addEventListener("keydown", this.handleKeys);
159 baseGameDiv.addEventListener("wheel", this.handleScroll);
162 document.getElementById("eogDiv"),
163 document.getElementById("adjuster")
164 ].forEach(elt => elt.addEventListener("click", processModalClick));
165 // Take full width on small screens:
166 let boardSize = parseInt(localStorage.getItem("boardSize"));
169 window.innerWidth >= 768
170 ? 0.75 * Math.min(window.innerWidth, window.innerHeight)
173 const movesWidth = window.innerWidth >= 768 ? 280 : 0;
174 document.getElementById("boardContainer").style.width = boardSize + "px";
175 let gameContainer = document.getElementById("gameContainer");
176 gameContainer.style.width = boardSize + movesWidth + "px";
177 document.getElementById("boardSize").value =
178 (boardSize * 100) / (window.innerWidth - movesWidth);
179 // timeout to avoid calling too many time the adjust method
180 let timeoutLaunched = false;
181 window.addEventListener("resize", () => {
182 if (!timeoutLaunched) {
183 timeoutLaunched = true;
186 timeoutLaunched = false;
192 focusBg: function() {
193 document.getElementById("baseGame").focus();
195 adjustBoard: function() {
196 const boardContainer = document.getElementById("boardContainer");
197 if (!boardContainer) return; //no board on page
198 const k = document.getElementById("boardSize").value;
199 const movesWidth = window.innerWidth >= 768 ? 280 : 0;
200 const minBoardWidth = 240; //TODO: these 240 and 280 are arbitrary...
201 // Value of 0 is board min size; 100 is window.width [- movesWidth]
204 (k * (window.innerWidth - (movesWidth + minBoardWidth))) / 100;
205 localStorage.setItem("boardSize", boardSize);
206 boardContainer.style.width = boardSize + "px";
207 document.getElementById("gameContainer").style.width =
208 boardSize + movesWidth + "px";
210 handleKeys: function(e) {
211 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
230 handleScroll: function(e) {
232 if (e.deltaY < 0) this.undo();
233 else if (e.deltaY > 0) this.play();
235 showRules: function() {
236 //this.$router.push("/variants/" + this.game.vname);
237 window.open("#/variants/" + this.game.vname, "_blank"); //better
239 re_setVariables: function() {
240 this.endgameMessage = "";
241 // "w": default orientation for observed games
242 this.orientation = this.game.mycolor || "w";
243 this.moves = JSON.parse(JSON.stringify(this.game.moves || []));
244 // Post-processing: decorate each move with notation and FEN
245 this.vr = new V(this.game.fenStart);
246 const parsedFen = V.ParseFen(this.game.fenStart);
247 const firstMoveColor = parsedFen.turn;
248 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2);
249 this.moves.forEach(move => {
250 // Strategy working also for multi-moves:
251 if (!Array.isArray(move)) move = [move];
253 m.notation = this.vr.getNotation(m);
257 if (firstMoveColor == "b") {
258 // 'end' is required for Board component to check lastMove for e.p.
261 end: { x: -1, y: -1 }
264 this.positionCursorTo(this.moves.length - 1);
265 this.incheck = this.vr.getCheckSquares(this.vr.turn);
267 positionCursorTo: function(index) {
269 // Caution: last move in moves array might be a multi-move
271 if (Array.isArray(this.moves[index])) {
272 const L = this.moves[index].length;
273 this.lastMove = this.moves[index][L - 1];
275 this.lastMove = this.moves[index];
279 this.lastMove = null;
281 analyzePosition: function() {
286 this.vr.getFen().replace(/ /g, "_");
287 // Open in same tab in live games (against cheating)
288 if (this.game.type == "live") this.$router.push(newUrl);
289 else window.open("#" + newUrl);
291 download: function() {
292 const content = this.getPgn();
293 // Prepare and trigger download link
294 let downloadAnchor = document.getElementById("download");
295 downloadAnchor.setAttribute("download", "game.pgn");
296 downloadAnchor.href =
297 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
298 downloadAnchor.click();
302 pgn += '[Site "vchess.club"]\n';
303 pgn += '[Variant "' + this.game.vname + '"]\n';
304 pgn += '[Date "' + getDate(new Date()) + '"]\n';
305 pgn += '[White "' + this.game.players[0].name + '"]\n';
306 pgn += '[Black "' + this.game.players[1].name + '"]\n';
307 pgn += '[Fen "' + this.game.fenStart + '"]\n';
308 pgn += '[Result "' + this.game.score + '"]\n\n';
309 for (let i = 0; i < this.moves.length; i += 2) {
310 pgn += (i/2+1) + "." + getFullNotation(this.moves[i]) + " ";
311 if (i+1 < this.moves.length)
312 pgn += getFullNotation(this.moves[i+1]) + " ";
316 showEndgameMsg: function(message) {
317 this.endgameMessage = message;
318 let modalBox = document.getElementById("modalEog");
319 modalBox.checked = true;
321 modalBox.checked = false;
324 // Animate an elementary move
325 animateMove: function(move, callback) {
326 let startSquare = document.getElementById(getSquareId(move.start));
327 let endSquare = document.getElementById(getSquareId(move.end));
328 let rectStart = startSquare.getBoundingClientRect();
329 let rectEnd = endSquare.getBoundingClientRect();
331 x: rectEnd.x - rectStart.x,
332 y: rectEnd.y - rectStart.y
334 let movingPiece = document.querySelector(
335 "#" + getSquareId(move.start) + " > img.piece"
337 // HACK for animation (with positive translate, image slides "under background")
338 // Possible improvement: just alter squares on the piece's way...
339 const squares = document.getElementsByClassName("board");
340 for (let i = 0; i < squares.length; i++) {
341 let square = squares.item(i);
342 if (square.id != getSquareId(move.start)) square.style.zIndex = "-1";
344 movingPiece.style.transform =
345 "translate(" + translation.x + "px," + translation.y + "px)";
346 movingPiece.style.transitionDuration = "0.25s";
347 movingPiece.style.zIndex = "3000";
349 for (let i = 0; i < squares.length; i++)
350 squares.item(i).style.zIndex = "auto";
351 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
355 // "light": if gotoMove() or gotoEnd()
356 // data: some custom data (addTime) to be re-emitted
357 play: function(move, received, light, data) {
358 const navigate = !move;
359 const playSubmove = (smove) => {
360 if (!navigate) smove.notation = this.vr.getNotation(smove);
362 this.lastMove = smove;
363 // Is opponent in check?
364 this.incheck = this.vr.getCheckSquares(this.vr.turn);
366 if (!this.inMultimove) {
367 if (this.cursor < this.moves.length - 1)
368 this.moves = this.moves.slice(0, Math.max(this.cursor, 0));
369 this.moves.push(smove);
370 this.inMultimove = true; //potentially
373 // Already in the middle of a multi-move
374 const L = this.moves.length;
375 if (!Array.isArray(this.moves[L-1]))
376 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
378 this.$set(this.moves, L-1, this.moves.concat([smove]));
382 const playMove = () => {
383 const animate = V.ShowMoves == "all" && received;
384 if (!Array.isArray(move)) move = [move];
387 const initurn = this.vr.turn;
388 (function executeMove() {
389 const smove = move[moveIdx++];
391 self.animateMove(smove, () => {
393 if (moveIdx < move.length)
394 setTimeout(executeMove, 500);
395 else afterMove(smove, initurn);
399 if (moveIdx < move.length) executeMove();
400 else afterMove(smove, initurn);
404 const afterMove = (smove, initurn) => {
405 if (this.st.settings.sound == 2)
406 new Audio("/sounds/move.mp3").play().catch(() => {});
407 if (this.vr.turn != initurn) {
408 // Turn has changed: move is complete
409 this.inMultimove = false;
410 const score = this.vr.getCurrentScore();
412 const message = getScoreMessage(score);
413 if (!navigate && this.game.mode != "analyze")
414 this.$emit("gameover", score, message);
415 // Just show score on screen (allow undo)
416 else this.showEndgameMsg(score + " . " + message);
418 if (!navigate && this.game.mode != "analyze") {
419 const L = this.moves.length;
420 // Post-processing (e.g. computer play)
421 this.$emit("newmove", this.moves[L-1], data);
425 // NOTE: navigate and received are mutually exclusive
427 // The move to navigate to is necessarily full:
428 if (this.cursor == this.moves.length - 1) return; //no more moves
429 move = this.moves[this.cursor + 1];
431 // Just play the move, nothing else:
432 if (!Array.isArray(move)) move = [move];
433 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
439 // Forbid playing outside analyze mode, except if move is received.
440 // Sufficient condition because Board already knows which turn it is.
442 this.game.mode != "analyze" &&
444 (this.game.score != "*" || this.cursor < this.moves.length - 1)
448 // To play a received move, cursor must be at the end of the game:
449 if (received && this.cursor < this.moves.length - 1)
453 cancelCurrentMultimove: function() {
454 // Cancel current multi-move
455 const L = this.moves.length;
456 let move = this.moves[L-1];
457 if (!Array.isArray(move)) move = [move];
458 for (let i=move.length -1; i >= 0; i--) this.vr.undo(move[i]);
461 this.inMultimove = false;
463 cancelLastMove: function() {
464 // The last played move was canceled (corr game)
468 // "light": if gotoMove() or gotoBegin()
469 undo: function(move, light) {
470 if (this.inMultimove) {
471 this.cancelCurrentMultimove();
472 this.incheck = this.vr.getCheckSquares(this.vr.turn);
475 if (this.cursor < 0) return; //no more moves
476 move = this.moves[this.cursor];
478 // Caution; if multi-move, undo all submoves from last to first
479 undoMove(move, this.vr);
480 if (light) this.cursor--;
482 this.positionCursorTo(this.cursor - 1);
483 if (this.st.settings.sound == 2)
484 new Audio("/sounds/undo.mp3").play().catch(() => {});
485 this.incheck = this.vr.getCheckSquares(this.vr.turn);
489 gotoMove: function(index) {
490 if (this.inMultimove) this.cancelCurrentMultimove();
491 if (index == this.cursor) return;
492 if (index < this.cursor) {
493 while (this.cursor > index)
494 this.undo(null, null, "light");
497 // index > this.cursor)
498 while (this.cursor < index)
499 this.play(null, null, "light");
501 // NOTE: next line also re-assign cursor, but it's very light
502 this.positionCursorTo(index);
503 this.incheck = this.vr.getCheckSquares(this.vr.turn);
505 gotoBegin: function() {
506 if (this.inMultimove) this.cancelCurrentMultimove();
507 while (this.cursor >= 0)
508 this.undo(null, null, "light");
509 if (this.moves.length > 0 && this.moves[0].notation == "...") {
511 this.lastMove = this.moves[0];
513 this.lastMove = null;
517 gotoEnd: function() {
518 if (this.cursor == this.moves.length - 1) return;
519 this.gotoMove(this.moves.length - 1);
522 this.orientation = V.GetOppCol(this.orientation);
528 <style lang="sass" scoped>
529 [type="checkbox"]#modalEog+div .card
532 [type="checkbox"]#modalAdjust+div .card
545 display: inline-block
551 display: inline-block
560 border-top: 1px solid #2f4f4f
568 border-left: 1px solid #2f4f4f
573 // TODO: later, maybe, allow movesList of variable width
574 // or e.g. between 250 and 350px (but more complicated)
580 @media screen and (max-width: 767px)