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