Still logging an issue when transitioning Hall <--> Game (button Available/Playing...
[vchess.git] / client / src / components / BaseGame.vue
1 <template lang="pug">
2 div#baseGame(tabindex=-1 @click="() => focusBg()"
3 @keydown="handleKeys" @wheel="handleScroll")
4 input#modalEog.modal(type="checkbox")
5 div#eogDiv(role="dialog" data-checkbox="modalEog" aria-labelledby="eogMessage")
6 .card.smallpad.small-modal.text-center
7 label.modal-close(for="modalEog")
8 h3#eogMessage.section {{ endgameMessage }}
9 input#modalAdjust.modal(type="checkbox")
10 div#adjuster(role="dialog" data-checkbox="modalAdjust" aria-labelledby="labelAdjust")
11 .card.smallpad.small-modal.text-center
12 label.modal-close(for="modalAdjust")
13 label#labelAdjust(for="boardSize") {{ st.tr["Board size"] }}
14 input#boardSize.slider(type="range" min="0" max="100" value="50"
15 @input="adjustBoard")
16 #gameContainer
17 #boardContainer
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=='*'")
22 | {{ turn }}
23 #controls
24 button(@click="gotoBegin") <<
25 button(@click="() => undo()") <
26 button(@click="flip") &#8645;
27 button(@click="() => play()") >
28 button(@click="gotoEnd") >>
29 #pgnDiv
30 #downloadDiv(v-if="game.vname!='Dark' || game.score!='*'")
31 a#download(href="#")
32 button(@click="download") {{ st.tr["Download PGN"] }}
33 button(onClick="doClick('modalAdjust')") &#10530;
34 button(v-if="game.vname!='Dark' && game.mode!='analyze'"
35 @click="analyzePosition")
36 | {{ st.tr["Analyze"] }}
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"] }}
40 #movesList
41 MoveList(v-if="showMoves" :score="game.score" :message="game.scoreMsg"
42 :firstNum="firstMoveNumber" :moves="moves" :cursor="cursor"
43 @goto-move="gotoMove")
44 .clearer
45 </template>
46
47 <script>
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";
55
56 export default {
57 name: 'my-base-game',
58 components: {
59 Board,
60 MoveList,
61 },
62 // "vr": VariantRules object, describing the game state + rules
63 props: ["vr","game"],
64 data: function() {
65 return {
66 st: store.state,
67 // NOTE: all following variables must be reset at the beginning of a game
68 endgameMessage: "",
69 orientation: "w",
70 score: "*", //'*' means 'unfinished'
71 moves: [],
72 cursor: -1, //index of the move just played
73 lastMove: null,
74 firstMoveNumber: 0, //for printing
75 incheck: [], //for Board
76 };
77 },
78 watch: {
79 // game initial FEN changes when a new game starts
80 "game.fenStart": function() {
81 this.re_setVariables();
82 },
83 // Received a new move to play:
84 // TODO: error "flush nextTick callbacks" when observer reloads page
85 "game.moveToPlay": function(newMove) {
86 if (!!newMove) //if stop + launch new game, get undefined move
87 this.play(newMove, "receive");
88 },
89 },
90 computed: {
91 showMoves: function() {
92 return this.game.vname != "Dark" || this.game.score != "*";
93 },
94 turn: function() {
95 let color = "";
96 const L = this.moves.length;
97 if (L == 0 || this.moves[L-1].color == "b")
98 color = "White";
99 else //if (this.moves[L-1].color == "w")
100 color = "Black";
101 return this.st.tr[color + " to move"];
102 },
103 analyze: function() {
104 return this.game.mode=="analyze" ||
105 // From Board viewpoint, a finished Dark game == analyze (TODO: unclear)
106 (this.game.vname == "Dark" && this.game.score != "*");
107 },
108 },
109 created: function() {
110 if (!!this.game.fenStart)
111 this.re_setVariables();
112 },
113 mounted: function() {
114 [document.getElementById("eogDiv"),document.getElementById("adjuster")]
115 .forEach(elt => elt.addEventListener("click", processModalClick));
116 // Take full width on small screens:
117 let boardSize = parseInt(localStorage.getItem("boardSize"));
118 if (!boardSize)
119 {
120 boardSize = (window.innerWidth >= 768
121 ? Math.min(600, 0.5*window.innerWidth) //heuristic...
122 : window.innerWidth);
123 }
124 const movesWidth = (window.innerWidth >= 768 ? 280 : 0);
125 document.getElementById("boardContainer").style.width = boardSize + "px";
126 let gameContainer = document.getElementById("gameContainer");
127 gameContainer.style.width = (boardSize + movesWidth) + "px";
128 // TODO: find the right formula here:
129 //document.getElementById("boardSize").value = Math.floor(boardSize / 10);
130 // timeout to avoid calling too many time the adjust method
131 let timeoutLaunched = false;
132 window.addEventListener("resize", (e) => {
133 if (!timeoutLaunched)
134 {
135 timeoutLaunched = true;
136 setTimeout( () => {
137 this.adjustBoard();
138 timeoutLaunched = false;
139 }, 500);
140 }
141 });
142 },
143 methods: {
144 focusBg: function() {
145 // NOTE: small blue border appears...
146 document.getElementById("baseGame").focus();
147 },
148 adjustBoard: function() {
149 const boardContainer = document.getElementById("boardContainer");
150 if (!boardContainer)
151 return; //no board on page
152 const k = document.getElementById("boardSize").value;
153 const movesWidth = (window.innerWidth >= 768 ? 280 : 0);
154 const minBoardWidth = 240; //TODO: these 240 and 280 are arbitrary...
155 // Value of 0 is board min size; 100 is window.width [- movesWidth]
156 const boardSize = minBoardWidth +
157 k * (window.innerWidth - (movesWidth+minBoardWidth)) / 100;
158 localStorage.setItem("boardSize", boardSize);
159 boardContainer.style.width = boardSize + "px";
160 document.getElementById("gameContainer").style.width =
161 (boardSize + movesWidth) + "px";
162 },
163 handleKeys: function(e) {
164 if ([32,37,38,39,40].includes(e.keyCode))
165 e.preventDefault();
166 switch (e.keyCode)
167 {
168 case 37:
169 this.undo();
170 break;
171 case 39:
172 this.play();
173 break;
174 case 38:
175 this.gotoBegin();
176 break;
177 case 40:
178 this.gotoEnd();
179 break;
180 case 32:
181 this.flip();
182 break;
183 }
184 },
185 handleScroll: function(e) {
186 // NOTE: since game.mode=="analyze" => no score, next condition is enough
187 if (this.game.score != "*")
188 {
189 e.preventDefault();
190 if (e.deltaY < 0)
191 this.undo();
192 else if (e.deltaY > 0)
193 this.play();
194 }
195 },
196 showRules: function() {
197 //this.$router.push("/variants/" + this.game.vname);
198 window.open("#/variants/" + this.game.vname, "_blank"); //better
199 },
200 re_setVariables: function() {
201 this.endgameMessage = "";
202 this.orientation = this.game.mycolor || "w"; //default orientation for observed games
203 this.moves = JSON.parse(JSON.stringify(this.game.moves || []));
204 // Post-processing: decorate each move with color + current FEN:
205 // (to be able to jump to any position quickly)
206 let vr_tmp = new V(this.game.fenStart); //vr is already at end of game
207 this.firstMoveNumber =
208 Math.floor(V.ParseFen(this.game.fenStart).movesCount / 2);
209 this.moves.forEach(move => {
210 // NOTE: this is doing manually what play() function below achieve,
211 // but in a lighter "fast-forward" way
212 move.color = vr_tmp.turn;
213 move.notation = vr_tmp.getNotation(move);
214 vr_tmp.play(move);
215 move.fen = vr_tmp.getFen();
216 });
217 if (this.game.fenStart.indexOf(" b ") >= 0 ||
218 (this.moves.length > 0 && this.moves[0].color == "b"))
219 {
220 // 'end' is required for Board component to check lastMove for e.p.
221 this.moves.unshift({color: "w", notation: "...", end: {x:-1,y:-1}});
222 }
223 const L = this.moves.length;
224 this.cursor = L-1;
225 this.lastMove = (L > 0 ? this.moves[L-1] : null);
226 },
227 analyzePosition: function() {
228 const newUrl = "/analyze/" + this.game.vname +
229 "/?fen=" + this.vr.getFen().replace(/ /g, "_");
230 if (this.game.type == "live")
231 this.$router.push(newUrl); //open in same tab: against cheating...
232 else
233 window.open("#" + newUrl); //open in a new tab: more comfortable
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 = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
241 downloadAnchor.click();
242 },
243 getPgn: function() {
244 let pgn = "";
245 pgn += '[Site "vchess.club"]\n';
246 pgn += '[Variant "' + this.game.vname + '"]\n';
247 pgn += '[Date "' + getDate(new Date()) + '"]\n';
248 pgn += '[White "' + this.game.players[0].name + '"]\n';
249 pgn += '[Black "' + this.game.players[1].name + '"]\n';
250 pgn += '[Fen "' + this.game.fenStart + '"]\n';
251 pgn += '[Result "' + this.game.score + '"]\n\n';
252 let counter = 1;
253 let i = 0;
254 while (i < this.moves.length)
255 {
256 pgn += (counter++) + ".";
257 for (let color of ["w","b"])
258 {
259 let move = "";
260 while (i < this.moves.length && this.moves[i].color == color)
261 move += this.moves[i++].notation + ",";
262 move = move.slice(0,-1); //remove last comma
263 pgn += move + (i < this.moves.length ? " " : "");
264 }
265 }
266 return pgn + "\n";
267 },
268 showEndgameMsg: function(message) {
269 this.endgameMessage = message;
270 let modalBox = document.getElementById("modalEog");
271 modalBox.checked = true;
272 setTimeout(() => { modalBox.checked = false; }, 2000);
273 },
274 animateMove: function(move, callback) {
275 let startSquare = document.getElementById(getSquareId(move.start));
276 let endSquare = document.getElementById(getSquareId(move.end));
277 let rectStart = startSquare.getBoundingClientRect();
278 let rectEnd = endSquare.getBoundingClientRect();
279 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
280 let movingPiece =
281 document.querySelector("#" + getSquareId(move.start) + " > img.piece");
282 // HACK for animation (with positive translate, image slides "under background")
283 // Possible improvement: just alter squares on the piece's way...
284 const squares = document.getElementsByClassName("board");
285 for (let i=0; i<squares.length; i++)
286 {
287 let square = squares.item(i);
288 if (square.id != getSquareId(move.start))
289 square.style.zIndex = "-1";
290 }
291 movingPiece.style.transform = "translate(" + translation.x + "px," +
292 translation.y + "px)";
293 movingPiece.style.transitionDuration = "0.2s";
294 movingPiece.style.zIndex = "3000";
295 setTimeout( () => {
296 for (let i=0; i<squares.length; i++)
297 squares.item(i).style.zIndex = "auto";
298 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
299 callback();
300 }, 250);
301 },
302 play: function(move, receive) {
303 // NOTE: navigate and receive are mutually exclusive
304 const navigate = !move;
305 // Forbid playing outside analyze mode, except if move is received.
306 // Sufficient condition because Board already knows which turn it is.
307 if (!navigate && this.game.mode!="analyze" && !receive
308 && (this.game.score != "*" || this.cursor < this.moves.length-1))
309 {
310 return;
311 }
312 const doPlayMove = () => {
313 if (!!receive && this.cursor < this.moves.length-1)
314 this.gotoEnd(); //required to play the move
315 if (navigate)
316 {
317 if (this.cursor == this.moves.length-1)
318 return; //no more moves
319 move = this.moves[this.cursor+1];
320 }
321 else
322 {
323 move.color = this.vr.turn;
324 move.notation = this.vr.getNotation(move);
325 }
326 this.vr.play(move);
327 this.cursor++;
328 this.lastMove = move;
329 if (this.st.settings.sound == 2)
330 new Audio("/sounds/move.mp3").play().catch(err => {});
331 if (!navigate)
332 {
333 move.fen = this.vr.getFen();
334 // Stack move on movesList at current cursor
335 if (this.cursor == this.moves.length)
336 this.moves.push(move);
337 else
338 this.moves = this.moves.slice(0,this.cursor).concat([move]);
339 }
340 // Is opponent in check?
341 this.incheck = this.vr.getCheckSquares(this.vr.turn);
342 const score = this.vr.getCurrentScore();
343 if (score != "*")
344 {
345 const message = getScoreMessage(score);
346 if (this.game.mode != "analyze")
347 this.$emit("gameover", score, message);
348 else //just show score on screen (allow undo)
349 this.showEndgameMsg(score + " . " + message);
350 }
351 if (!navigate && this.game.mode!="analyze")
352 this.$emit("newmove", move); //post-processing (e.g. computer play)
353 };
354 if (!!receive && this.game.vname != "Dark")
355 this.animateMove(move, doPlayMove);
356 else
357 doPlayMove();
358 },
359 undo: function(move) {
360 const navigate = !move;
361 if (navigate)
362 {
363 if (this.cursor < 0)
364 return; //no more moves
365 move = this.moves[this.cursor];
366 }
367 this.vr.undo(move);
368 this.cursor--;
369 this.lastMove = (this.cursor >= 0 ? this.moves[this.cursor] : undefined);
370 if (this.st.settings.sound == 2)
371 new Audio("/sounds/undo.mp3").play().catch(err => {});
372 this.incheck = this.vr.getCheckSquares(this.vr.turn);
373 if (!navigate)
374 this.moves.pop();
375 },
376 gotoMove: function(index) {
377 this.vr.re_init(this.moves[index].fen);
378 this.cursor = index;
379 this.lastMove = this.moves[index];
380 },
381 gotoBegin: function() {
382 if (this.cursor == -1)
383 return;
384 this.vr.re_init(this.game.fenStart);
385 if (this.moves.length > 0 && this.moves[0].notation == "...")
386 {
387 this.cursor = 0;
388 this.lastMove = this.moves[0];
389 }
390 else
391 {
392 this.cursor = -1;
393 this.lastMove = null;
394 }
395 },
396 gotoEnd: function() {
397 if (this.cursor == this.moves.length - 1)
398 return;
399 this.gotoMove(this.moves.length-1);
400 },
401 flip: function() {
402 this.orientation = V.GetOppCol(this.orientation);
403 },
404 },
405 };
406 </script>
407
408 <style lang="sass" scoped>
409 #baseGame
410 width: 100%
411 &:focus
412 outline: none
413
414 #gameContainer
415 margin-left: auto
416 margin-right: auto
417
418 #downloadDiv
419 display: inline-block
420
421 #modal-eog+div .card
422 overflow: hidden
423 #controls
424 margin-top: 10px
425 margin-left: auto
426 margin-right: auto
427 button
428 display: inline-block
429 width: 20%
430 margin: 0
431 @media screen and (min-width: 768px)
432 #controls
433 max-width: 400px
434 #turnIndicator
435 text-align: center
436 #pgnDiv
437 text-align: center
438 margin-left: auto
439 margin-right: auto
440 #boardContainer
441 float: left
442 // TODO: later, maybe, allow movesList of variable width
443 // or e.g. between 250 and 350px (but more complicated)
444 #movesList
445 width: 280px
446 float: left
447 @media screen and (max-width: 767px)
448 #movesList
449 width: 100%
450 float: none
451 clear: both
452 </style>