Fixes about lastate
[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 "game.moveToPlay": function(newMove) {
85 if (!!newMove) //if stop + launch new game, get undefined move
86 this.play(newMove, "receive");
87 },
88 },
89 computed: {
90 showMoves: function() {
91 return this.game.vname != "Dark" || this.game.score != "*";
92 },
93 turn: function() {
94 let color = "";
95 const L = this.moves.length;
96 if (L == 0 || this.moves[L-1].color == "b")
97 color = "White";
98 else //if (this.moves[L-1].color == "w")
99 color = "Black";
100 return this.st.tr[color + " to move"];
101 },
102 analyze: function() {
103 return this.game.mode=="analyze" ||
104 // From Board viewpoint, a finished Dark game == analyze (TODO: unclear)
105 (this.game.vname == "Dark" && this.game.score != "*");
106 },
107 },
108 created: function() {
109 if (!!this.game.fenStart)
110 this.re_setVariables();
111 },
112 mounted: function() {
113 [document.getElementById("eogDiv"),document.getElementById("adjuster")]
114 .forEach(elt => elt.addEventListener("click", processModalClick));
115 // Take full width on small screens:
116 let boardSize = parseInt(localStorage.getItem("boardSize"));
117 if (!boardSize)
118 {
119 boardSize = (window.innerWidth >= 768
120 ? Math.min(600, 0.5*window.innerWidth) //heuristic...
121 : window.innerWidth);
122 }
123 const movesWidth = (window.innerWidth >= 768 ? 280 : 0);
124 document.getElementById("boardContainer").style.width = boardSize + "px";
125 let gameContainer = document.getElementById("gameContainer");
126 gameContainer.style.width = (boardSize + movesWidth) + "px";
127 // TODO: find the right formula here:
128 //document.getElementById("boardSize").value = Math.floor(boardSize / 10);
129 // timeout to avoid calling too many time the adjust method
130 let timeoutLaunched = false;
131 window.addEventListener("resize", (e) => {
132 if (!timeoutLaunched)
133 {
134 timeoutLaunched = true;
135 setTimeout( () => {
136 this.adjustBoard();
137 timeoutLaunched = false;
138 }, 500);
139 }
140 });
141 },
142 methods: {
143 focusBg: function() {
144 // NOTE: small blue border appears...
145 document.getElementById("baseGame").focus();
146 },
147 adjustBoard: function() {
148 const boardContainer = document.getElementById("boardContainer");
149 if (!boardContainer)
150 return; //no board on page
151 const k = document.getElementById("boardSize").value;
152 const movesWidth = (window.innerWidth >= 768 ? 280 : 0);
153 const minBoardWidth = 240; //TODO: these 240 and 280 are arbitrary...
154 // Value of 0 is board min size; 100 is window.width [- movesWidth]
155 const boardSize = minBoardWidth +
156 k * (window.innerWidth - (movesWidth+minBoardWidth)) / 100;
157 localStorage.setItem("boardSize", boardSize);
158 boardContainer.style.width = boardSize + "px";
159 document.getElementById("gameContainer").style.width =
160 (boardSize + movesWidth) + "px";
161 },
162 handleKeys: function(e) {
163 if ([32,37,38,39,40].includes(e.keyCode))
164 e.preventDefault();
165 switch (e.keyCode)
166 {
167 case 37:
168 this.undo();
169 break;
170 case 39:
171 this.play();
172 break;
173 case 38:
174 this.gotoBegin();
175 break;
176 case 40:
177 this.gotoEnd();
178 break;
179 case 32:
180 this.flip();
181 break;
182 }
183 },
184 handleScroll: function(e) {
185 // NOTE: since game.mode=="analyze" => no score, next condition is enough
186 if (this.game.score != "*")
187 {
188 e.preventDefault();
189 if (e.deltaY < 0)
190 this.undo();
191 else if (e.deltaY > 0)
192 this.play();
193 }
194 },
195 showRules: function() {
196 //this.$router.push("/variants/" + this.game.vname);
197 window.open("#/variants/" + this.game.vname, "_blank"); //better
198 },
199 re_setVariables: function() {
200 this.endgameMessage = "";
201 this.orientation = this.game.mycolor || "w"; //default orientation for observed games
202 this.moves = JSON.parse(JSON.stringify(this.game.moves || []));
203 // Post-processing: decorate each move with color + current FEN:
204 // (to be able to jump to any position quickly)
205 let vr_tmp = new V(this.game.fenStart); //vr is already at end of game
206 this.firstMoveNumber =
207 Math.floor(V.ParseFen(this.game.fenStart).movesCount / 2);
208 this.moves.forEach(move => {
209 // NOTE: this is doing manually what play() function below achieve,
210 // but in a lighter "fast-forward" way
211 move.color = vr_tmp.turn;
212 move.notation = vr_tmp.getNotation(move);
213 vr_tmp.play(move);
214 move.fen = vr_tmp.getFen();
215 });
216 if (this.game.fenStart.indexOf(" b ") >= 0 ||
217 (this.moves.length > 0 && this.moves[0].color == "b"))
218 {
219 // 'end' is required for Board component to check lastMove for e.p.
220 this.moves.unshift({color: "w", notation: "...", end: {x:-1,y:-1}});
221 }
222 const L = this.moves.length;
223 this.cursor = L-1;
224 this.lastMove = (L > 0 ? this.moves[L-1] : null);
225 this.incheck = [];
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 // TODO: error "flush nextTick callbacks" when observer reloads page:
277 // this late check is not a fix!
278 if (!startSquare)
279 return;
280 let endSquare = document.getElementById(getSquareId(move.end));
281 let rectStart = startSquare.getBoundingClientRect();
282 let rectEnd = endSquare.getBoundingClientRect();
283 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
284 let movingPiece =
285 document.querySelector("#" + getSquareId(move.start) + " > img.piece");
286 if (!movingPiece) //TODO: shouldn't happen
287 return;
288 // HACK for animation (with positive translate, image slides "under background")
289 // Possible improvement: just alter squares on the piece's way...
290 const squares = document.getElementsByClassName("board");
291 for (let i=0; i<squares.length; i++)
292 {
293 let square = squares.item(i);
294 if (square.id != getSquareId(move.start))
295 square.style.zIndex = "-1";
296 }
297 movingPiece.style.transform = "translate(" + translation.x + "px," +
298 translation.y + "px)";
299 movingPiece.style.transitionDuration = "0.2s";
300 movingPiece.style.zIndex = "3000";
301 setTimeout( () => {
302 for (let i=0; i<squares.length; i++)
303 squares.item(i).style.zIndex = "auto";
304 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
305 callback();
306 }, 250);
307 },
308 play: function(move, receive) {
309 // NOTE: navigate and receive are mutually exclusive
310 const navigate = !move;
311 // Forbid playing outside analyze mode, except if move is received.
312 // Sufficient condition because Board already knows which turn it is.
313 if (!navigate && this.game.mode!="analyze" && !receive
314 && (this.game.score != "*" || this.cursor < this.moves.length-1))
315 {
316 return;
317 }
318 const doPlayMove = () => {
319 if (!!receive && this.cursor < this.moves.length-1)
320 this.gotoEnd(); //required to play the move
321 if (navigate)
322 {
323 if (this.cursor == this.moves.length-1)
324 return; //no more moves
325 move = this.moves[this.cursor+1];
326 }
327 else
328 {
329 move.color = this.vr.turn;
330 move.notation = this.vr.getNotation(move);
331 }
332 this.vr.play(move);
333 this.cursor++;
334 this.lastMove = move;
335 if (this.st.settings.sound == 2)
336 new Audio("/sounds/move.mp3").play().catch(err => {});
337 if (!navigate)
338 {
339 move.fen = this.vr.getFen();
340 // Stack move on movesList at current cursor
341 if (this.cursor == this.moves.length)
342 this.moves.push(move);
343 else
344 this.moves = this.moves.slice(0,this.cursor).concat([move]);
345 }
346 // Is opponent in check?
347 this.incheck = this.vr.getCheckSquares(this.vr.turn);
348 const score = this.vr.getCurrentScore();
349 if (score != "*")
350 {
351 const message = getScoreMessage(score);
352 if (this.game.mode != "analyze")
353 this.$emit("gameover", score, message);
354 else //just show score on screen (allow undo)
355 this.showEndgameMsg(score + " . " + message);
356 }
357 if (!navigate && this.game.mode!="analyze")
358 this.$emit("newmove", move); //post-processing (e.g. computer play)
359 };
360 if (!!receive && this.game.vname != "Dark")
361 this.animateMove(move, doPlayMove);
362 else
363 doPlayMove();
364 },
365 undo: function(move) {
366 const navigate = !move;
367 if (navigate)
368 {
369 if (this.cursor < 0)
370 return; //no more moves
371 move = this.moves[this.cursor];
372 }
373 this.vr.undo(move);
374 this.cursor--;
375 this.lastMove = (this.cursor >= 0 ? this.moves[this.cursor] : undefined);
376 if (this.st.settings.sound == 2)
377 new Audio("/sounds/undo.mp3").play().catch(err => {});
378 this.incheck = this.vr.getCheckSquares(this.vr.turn);
379 if (!navigate)
380 this.moves.pop();
381 },
382 gotoMove: function(index) {
383 this.vr.re_init(this.moves[index].fen);
384 this.cursor = index;
385 this.lastMove = this.moves[index];
386 },
387 gotoBegin: function() {
388 if (this.cursor == -1)
389 return;
390 this.vr.re_init(this.game.fenStart);
391 if (this.moves.length > 0 && this.moves[0].notation == "...")
392 {
393 this.cursor = 0;
394 this.lastMove = this.moves[0];
395 }
396 else
397 {
398 this.cursor = -1;
399 this.lastMove = null;
400 }
401 },
402 gotoEnd: function() {
403 if (this.cursor == this.moves.length - 1)
404 return;
405 this.gotoMove(this.moves.length-1);
406 },
407 flip: function() {
408 this.orientation = V.GetOppCol(this.orientation);
409 },
410 },
411 };
412 </script>
413
414 <style lang="sass" scoped>
415 #baseGame
416 width: 100%
417 &:focus
418 outline: none
419
420 #gameContainer
421 margin-left: auto
422 margin-right: auto
423
424 #downloadDiv
425 display: inline-block
426
427 #modal-eog+div .card
428 overflow: hidden
429 #controls
430 margin-top: 10px
431 margin-left: auto
432 margin-right: auto
433 button
434 display: inline-block
435 width: 20%
436 margin: 0
437 @media screen and (min-width: 768px)
438 #controls
439 max-width: 400px
440 #turnIndicator
441 text-align: center
442 #pgnDiv
443 text-align: center
444 margin-left: auto
445 margin-right: auto
446 #boardContainer
447 float: left
448 // TODO: later, maybe, allow movesList of variable width
449 // or e.g. between 250 and 350px (but more complicated)
450 #movesList
451 width: 280px
452 float: left
453 @media screen and (max-width: 767px)
454 #movesList
455 width: 100%
456 float: none
457 clear: both
458 </style>