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