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