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