2 div#baseGame(tabindex=-1 @click="focusBg()"
3 @keydown="handleKeys($event)" @wheel="handleScroll($event)")
4 input#modalEog.modal(type="checkbox")
5 div#eogDiv(role="dialog" data-checkbox="modalEog")
7 label.modal-close(for="modalEog")
8 h3.section {{ endgameMessage }}
9 input#modalAdjust.modal(type="checkbox")
10 div#adjuster(role="dialog" data-checkbox="modalAdjust")
12 label.modal-close(for="modalAdjust")
13 label(for="boardSize") {{ st.tr["Board size"] }}
14 input#boardSize.slider(type="range" min="0" max="100" value="50"
15 @input="adjustBoard()")
18 Board(:vr="vr" :last-move="lastMove" :analyze="analyze"
19 :user-color="game.mycolor" :orientation="orientation"
20 :vname="game.vname" :incheck="incheck" @play-move="play")
21 #turnIndicator(v-if="game.vname=='Dark' && game.score=='*'")
24 button(@click="gotoBegin()") <<
25 button(@click="undo()") <
26 button(@click="flip()") ⇅
27 button(@click="play()") >
28 button(@click="gotoEnd()") >>
30 #downloadDiv(v-if="game.vname!='Dark' || game.score!='*'")
32 button(@click="download()") {{ st.tr["Download"] }} PGN
33 button(onClick="doClick('modalAdjust')") ⤢
34 button(v-if="game.vname!='Dark' && game.mode!='analyze'"
35 @click="analyzePosition()")
36 | {{ st.tr["Analyse"] }}
37 // NOTE: rather ugly hack to avoid showing twice "rules" link...
38 button(v-if="!$route.path.match('/variants/')" @click="showRules()")
39 | {{ st.tr["Rules"] }}
41 MoveList(v-if="showMoves" :score="game.score" :message="game.scoreMsg"
42 :firstNum="firstMoveNumber" :moves="moves" :cursor="cursor"
43 @goto-move="gotoMove")
48 import Board from "@/components/Board.vue";
49 import MoveList from "@/components/MoveList.vue";
50 import { store } from "@/store";
51 import { getSquareId } from "@/utils/squareId";
52 import { getDate } from "@/utils/datetime";
53 import { processModalClick } from "@/utils/modalClick";
54 import { getScoreMessage } from "@/utils/scoring";
61 // "vr": VariantRules object, describing the game state + rules
66 // NOTE: all following variables must be reset at the beginning of a game
69 score: "*", //'*' means 'unfinished'
71 cursor: -1, //index of the move just played
73 firstMoveNumber: 0, //for printing
74 incheck: [], //for Board
78 // game initial FEN changes when a new game starts
79 "game.fenStart": function() {
80 this.re_setVariables();
82 // Received a new move to play:
83 "game.moveToPlay": function(newMove) {
84 if (!!newMove) //if stop + launch new game, get undefined move
85 this.play(newMove, "receive");
87 // ...Or to undo (corr game, move not validated)
88 "game.moveToUndo": function(move) {
94 showMoves: function() {
95 return this.game.vname != "Dark" || this.game.score != "*";
99 const L = this.moves.length;
100 if (L == 0 || this.moves[L-1].color == "b")
102 else //if (this.moves[L-1].color == "w")
104 return this.st.tr[color + " to move"];
106 analyze: function() {
107 return this.game.mode=="analyze" ||
108 // From Board viewpoint, a finished Dark game == analyze (TODO: unclear)
109 (this.game.vname == "Dark" && this.game.score != "*");
112 created: function() {
113 if (!!this.game.fenStart)
114 this.re_setVariables();
116 mounted: function() {
117 [document.getElementById("eogDiv"),document.getElementById("adjuster")]
118 .forEach(elt => elt.addEventListener("click", processModalClick));
119 // Take full width on small screens:
120 let boardSize = parseInt(localStorage.getItem("boardSize"));
123 boardSize = (window.innerWidth >= 768
124 ? Math.min(600, 0.5*window.innerWidth) //heuristic...
125 : window.innerWidth);
127 const movesWidth = (window.innerWidth >= 768 ? 280 : 0);
128 document.getElementById("boardContainer").style.width = boardSize + "px";
129 let gameContainer = document.getElementById("gameContainer");
130 gameContainer.style.width = (boardSize + movesWidth) + "px";
131 // TODO: find the right formula here:
132 //document.getElementById("boardSize").value = Math.floor(boardSize / 10);
133 // timeout to avoid calling too many time the adjust method
134 let timeoutLaunched = false;
135 window.addEventListener("resize", (e) => {
136 if (!timeoutLaunched)
138 timeoutLaunched = true;
141 timeoutLaunched = false;
147 focusBg: function() {
148 // NOTE: small blue border appears...
149 document.getElementById("baseGame").focus();
151 adjustBoard: function() {
152 const boardContainer = document.getElementById("boardContainer");
154 return; //no board on page
155 const k = document.getElementById("boardSize").value;
156 const movesWidth = (window.innerWidth >= 768 ? 280 : 0);
157 const minBoardWidth = 240; //TODO: these 240 and 280 are arbitrary...
158 // Value of 0 is board min size; 100 is window.width [- movesWidth]
159 const boardSize = minBoardWidth +
160 k * (window.innerWidth - (movesWidth+minBoardWidth)) / 100;
161 localStorage.setItem("boardSize", boardSize);
162 boardContainer.style.width = boardSize + "px";
163 document.getElementById("gameContainer").style.width =
164 (boardSize + movesWidth) + "px";
166 handleKeys: function(e) {
167 if ([32,37,38,39,40].includes(e.keyCode))
188 handleScroll: function(e) {
189 // NOTE: since game.mode=="analyze" => no score, next condition is enough
190 if (this.game.score != "*")
195 else if (e.deltaY > 0)
199 showRules: function() {
200 //this.$router.push("/variants/" + this.game.vname);
201 window.open("#/variants/" + this.game.vname, "_blank"); //better
203 re_setVariables: function() {
204 this.endgameMessage = "";
205 this.orientation = this.game.mycolor || "w"; //default orientation for observed games
206 this.moves = JSON.parse(JSON.stringify(this.game.moves || []));
207 // Post-processing: decorate each move with color + current FEN:
208 // (to be able to jump to any position quickly)
209 let vr_tmp = new V(this.game.fenStart); //vr is already at end of game
210 this.firstMoveNumber =
211 Math.floor(V.ParseFen(this.game.fenStart).movesCount / 2);
212 this.moves.forEach(move => {
213 // NOTE: this is doing manually what play() function below achieve,
214 // but in a lighter "fast-forward" way
215 move.color = vr_tmp.turn;
216 move.notation = vr_tmp.getNotation(move);
218 move.fen = vr_tmp.getFen();
220 if (this.game.fenStart.indexOf(" b ") >= 0 ||
221 (this.moves.length > 0 && this.moves[0].color == "b"))
223 // 'end' is required for Board component to check lastMove for e.p.
224 this.moves.unshift({color: "w", notation: "...", end: {x:-1,y:-1}});
226 const L = this.moves.length;
228 this.lastMove = (L > 0 ? this.moves[L-1] : null);
231 analyzePosition: function() {
232 const newUrl = "/analyse/" + this.game.vname +
233 "/?fen=" + this.vr.getFen().replace(/ /g, "_");
234 if (this.game.type == "live")
235 this.$router.push(newUrl); //open in same tab: against cheating...
237 window.open("#" + newUrl); //open in a new tab: more comfortable
239 download: function() {
240 const content = this.getPgn();
241 // Prepare and trigger download link
242 let downloadAnchor = document.getElementById("download");
243 downloadAnchor.setAttribute("download", "game.pgn");
244 downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
245 downloadAnchor.click();
249 pgn += '[Site "vchess.club"]\n';
250 pgn += '[Variant "' + this.game.vname + '"]\n';
251 pgn += '[Date "' + getDate(new Date()) + '"]\n';
252 pgn += '[White "' + this.game.players[0].name + '"]\n';
253 pgn += '[Black "' + this.game.players[1].name + '"]\n';
254 pgn += '[Fen "' + this.game.fenStart + '"]\n';
255 pgn += '[Result "' + this.game.score + '"]\n\n';
258 while (i < this.moves.length)
260 pgn += (counter++) + ".";
261 for (let color of ["w","b"])
264 while (i < this.moves.length && this.moves[i].color == color)
265 move += this.moves[i++].notation + ",";
266 move = move.slice(0,-1); //remove last comma
267 pgn += move + (i < this.moves.length ? " " : "");
272 showEndgameMsg: function(message) {
273 this.endgameMessage = message;
274 let modalBox = document.getElementById("modalEog");
275 modalBox.checked = true;
276 setTimeout(() => { modalBox.checked = false; }, 2000);
278 animateMove: function(move, callback) {
279 let startSquare = document.getElementById(getSquareId(move.start));
280 // TODO: error "flush nextTick callbacks" when observer reloads page:
281 // this late check is not a fix!
284 let endSquare = document.getElementById(getSquareId(move.end));
285 let rectStart = startSquare.getBoundingClientRect();
286 let rectEnd = endSquare.getBoundingClientRect();
287 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
289 document.querySelector("#" + getSquareId(move.start) + " > img.piece");
290 if (!movingPiece) //TODO: shouldn't happen
292 // HACK for animation (with positive translate, image slides "under background")
293 // Possible improvement: just alter squares on the piece's way...
294 const squares = document.getElementsByClassName("board");
295 for (let i=0; i<squares.length; i++)
297 let square = squares.item(i);
298 if (square.id != getSquareId(move.start))
299 square.style.zIndex = "-1";
301 movingPiece.style.transform = "translate(" + translation.x + "px," +
302 translation.y + "px)";
303 movingPiece.style.transitionDuration = "0.2s";
304 movingPiece.style.zIndex = "3000";
306 for (let i=0; i<squares.length; i++)
307 squares.item(i).style.zIndex = "auto";
308 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
312 play: function(move, receive) {
313 // NOTE: navigate and receive are mutually exclusive
314 const navigate = !move;
315 // Forbid playing outside analyze mode, except if move is received.
316 // Sufficient condition because Board already knows which turn it is.
317 if (!navigate && this.game.mode!="analyze" && !receive
318 && (this.game.score != "*" || this.cursor < this.moves.length-1))
322 const doPlayMove = () => {
323 if (!!receive && this.cursor < this.moves.length-1)
324 this.gotoEnd(); //required to play the move
327 if (this.cursor == this.moves.length-1)
328 return; //no more moves
329 move = this.moves[this.cursor+1];
333 move.color = this.vr.turn;
334 move.notation = this.vr.getNotation(move);
338 this.lastMove = move;
339 if (this.st.settings.sound == 2)
340 new Audio("/sounds/move.mp3").play().catch(err => {});
343 move.fen = this.vr.getFen();
344 // Stack move on movesList at current cursor
345 if (this.cursor == this.moves.length)
346 this.moves.push(move);
348 this.moves = this.moves.slice(0,this.cursor).concat([move]);
350 // Is opponent in check?
351 this.incheck = this.vr.getCheckSquares(this.vr.turn);
352 const score = this.vr.getCurrentScore();
355 const message = getScoreMessage(score);
356 if (this.game.mode != "analyze")
357 this.$emit("gameover", score, message);
358 else //just show score on screen (allow undo)
359 this.showEndgameMsg(score + " . " + message);
361 if (!navigate && this.game.mode!="analyze")
362 this.$emit("newmove", move); //post-processing (e.g. computer play)
364 if (!!receive && this.game.vname != "Dark")
365 this.animateMove(move, doPlayMove);
369 undo: function(move) {
370 const navigate = !move;
374 return; //no more moves
375 move = this.moves[this.cursor];
379 this.lastMove = (this.cursor >= 0 ? this.moves[this.cursor] : undefined);
380 if (this.st.settings.sound == 2)
381 new Audio("/sounds/undo.mp3").play().catch(err => {});
382 this.incheck = this.vr.getCheckSquares(this.vr.turn);
386 gotoMove: function(index) {
387 this.vr.re_init(this.moves[index].fen);
389 this.lastMove = this.moves[index];
391 gotoBegin: function() {
392 if (this.cursor == -1)
394 this.vr.re_init(this.game.fenStart);
395 if (this.moves.length > 0 && this.moves[0].notation == "...")
398 this.lastMove = this.moves[0];
403 this.lastMove = null;
406 gotoEnd: function() {
407 if (this.cursor == this.moves.length - 1)
409 this.gotoMove(this.moves.length-1);
412 this.orientation = V.GetOppCol(this.orientation);
418 <style lang="sass" scoped>
419 [type="checkbox"]#modalEog+div .card
421 [type="checkbox"]#modalAdjust+div .card
434 display: inline-block
441 display: inline-block
444 @media screen and (min-width: 768px)
455 // TODO: later, maybe, allow movesList of variable width
456 // or e.g. between 250 and 350px (but more complicated)
460 @media screen and (max-width: 767px)