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