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