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