Adjustments, handle keyStrokes on BaseGame
[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 .col-sm-12.col-md-9.col-lg-8
10 Board(:vr="vr" :last-move="lastMove" :analyze="analyze"
11 :user-color="game.mycolor" :orientation="orientation"
12 :vname="game.vname" @play-move="play")
13 .button-group
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.col-lg-4
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 switch (e.keyCode)
97 {
98 case 37:
99 this.undo();
100 break;
101 case 39:
102 this.play();
103 break;
104 case 28:
105 this.gotoBegin();
106 break;
107 case 40:
108 this.gotoEnd();
109 break;
110 case 32:
111 e.preventDefault();
112 this.flip();
113 break;
114 }
115 },
116 re_setVariables: function() {
117 this.endgameMessage = "";
118 this.orientation = this.game.mycolor || "w"; //default orientation for observed games
119 this.score = this.game.score || "*"; //mutable (if initially "*")
120 this.gameHasEnded = (this.score != "*");
121 this.moves = JSON.parse(JSON.stringify(this.game.moves || []));
122 // Post-processing: decorate each move with color + current FEN:
123 // (to be able to jump to any position quickly)
124 let vr_tmp = new V(this.game.fenStart); //vr is already at end of game
125 this.moves.forEach(move => {
126 // NOTE: this is doing manually what play() function below achieve,
127 // but in a lighter "fast-forward" way
128 move.color = vr_tmp.turn;
129 move.notation = vr_tmp.getNotation(move);
130 vr_tmp.play(move);
131 move.fen = vr_tmp.getFen();
132 });
133 if (this.game.fenStart.indexOf(" b ") >= 0 ||
134 (this.moves.length > 0 && this.moves[0].color == "b"))
135 {
136 // 'end' is required for Board component to check lastMove for e.p.
137 this.moves.unshift({color: "w", notation: "...", end: {x:-1,y:-1}});
138 }
139 const L = this.moves.length;
140 this.cursor = L-1;
141 this.lastMove = (L > 0 ? this.moves[L-1] : null);
142 },
143 gotoFenContent: function(event) {
144 this.$router.push("/analyze/" + this.game.vname +
145 "/?fen=" + event.target.innerText.replace(/ /g, "_"));
146 },
147 download: function() {
148 const content = this.getPgn();
149 // Prepare and trigger download link
150 let downloadAnchor = document.getElementById("download");
151 downloadAnchor.setAttribute("download", "game.pgn");
152 downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
153 downloadAnchor.click();
154 },
155 getPgn: function() {
156 let pgn = "";
157 pgn += '[Site "vchess.club"]\n';
158 pgn += '[Variant "' + this.game.vname + '"]\n';
159 pgn += '[Date "' + getDate(new Date()) + '"]\n';
160 pgn += '[White "' + this.game.players[0].name + '"]\n';
161 pgn += '[Black "' + this.game.players[1].name + '"]\n';
162 pgn += '[Fen "' + this.game.fenStart + '"]\n';
163 pgn += '[Result "' + this.score + '"]\n\n';
164 let counter = 1;
165 let i = 0;
166 while (i < this.moves.length)
167 {
168 pgn += (counter++) + ".";
169 for (let color of ["w","b"])
170 {
171 let move = "";
172 while (i < this.moves.length && this.moves[i].color == color)
173 move += this.moves[i++].notation + ",";
174 move = move.slice(0,-1); //remove last comma
175 pgn += move + (i < this.moves.length ? " " : "");
176 }
177 }
178 return pgn + "\n";
179 },
180 getScoreMessage: function(score) {
181 let eogMessage = "Undefined";
182 switch (score)
183 {
184 case "1-0":
185 eogMessage = this.st.tr["White win"];
186 break;
187 case "0-1":
188 eogMessage = this.st.tr["Black win"];
189 break;
190 case "1/2":
191 eogMessage = this.st.tr["Draw"];
192 break;
193 case "?":
194 eogMessage = this.st.tr["Unfinished"];
195 break;
196 }
197 return eogMessage;
198 },
199 showEndgameMsg: function(message) {
200 this.endgameMessage = message;
201 let modalBox = document.getElementById("modalEog");
202 modalBox.checked = true;
203 setTimeout(() => { modalBox.checked = false; }, 2000);
204 },
205 endGame: function(score, message, bubbleUp) {
206 this.gameHasEnded = true;
207 this.score = score;
208 if (!message)
209 message = this.getScoreMessage(score);
210 this.showEndgameMsg(score + " . " + message);
211 if (bubbleUp)
212 this.$emit("gameover", score);
213 },
214 animateMove: function(move) {
215 let startSquare = document.getElementById(getSquareId(move.start));
216 let endSquare = document.getElementById(getSquareId(move.end));
217 let rectStart = startSquare.getBoundingClientRect();
218 let rectEnd = endSquare.getBoundingClientRect();
219 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
220 let movingPiece =
221 document.querySelector("#" + getSquareId(move.start) + " > img.piece");
222 // HACK for animation (with positive translate, image slides "under background")
223 // Possible improvement: just alter squares on the piece's way...
224 const squares = document.getElementsByClassName("board");
225 for (let i=0; i<squares.length; i++)
226 {
227 let square = squares.item(i);
228 if (square.id != getSquareId(move.start))
229 square.style.zIndex = "-1";
230 }
231 movingPiece.style.transform = "translate(" + translation.x + "px," +
232 translation.y + "px)";
233 movingPiece.style.transitionDuration = "0.2s";
234 movingPiece.style.zIndex = "3000";
235 setTimeout( () => {
236 for (let i=0; i<squares.length; i++)
237 squares.item(i).style.zIndex = "auto";
238 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
239 this.play(move);
240 }, 250);
241 },
242 play: function(move, receive, noanimate) {
243 const navigate = !move;
244 // Forbid playing outside analyze mode when cursor isn't at moves.length-1
245 // (except if we receive opponent's move, human or computer)
246 if (!navigate && !this.analyze && !receive
247 && this.cursor < this.moves.length-1)
248 {
249 return;
250 }
251 if (navigate)
252 {
253 if (this.cursor == this.moves.length-1)
254 return; //no more moves
255 move = this.moves[this.cursor+1];
256 }
257 if (!!receive && !noanimate) //opponent move, variant != "Dark"
258 {
259 if (this.cursor < this.moves.length-1)
260 this.gotoEnd(); //required to play the move
261 return this.animateMove(move);
262 }
263 if (!navigate)
264 {
265 move.color = this.vr.turn;
266 move.notation = this.vr.getNotation(move);
267 }
268 // Not programmatic, or animation is over
269 this.vr.play(move);
270 this.cursor++;
271 this.lastMove = move;
272 if (this.st.settings.sound == 2)
273 new Audio("/sounds/move.mp3").play().catch(err => {});
274 if (!navigate)
275 {
276 move.fen = this.vr.getFen();
277 if (this.score == "*" || this.analyze)
278 {
279 // Stack move on movesList at current cursor
280 if (this.cursor == this.moves.length)
281 this.moves.push(move);
282 else
283 this.moves = this.moves.slice(0,this.cursor).concat([move]);
284 }
285 }
286 if (!this.analyze)
287 this.$emit("newmove", move); //post-processing (e.g. computer play)
288 // Is opponent in check?
289 this.incheck = this.vr.getCheckSquares(this.vr.turn);
290 const score = this.vr.getCurrentScore();
291 if (score != "*")
292 {
293 if (!this.analyze)
294 this.endGame(score, undefined, true);
295 else
296 {
297 // Just show score on screen (allow undo)
298 const message = this.getScoreMessage(score);
299 this.showEndgameMsg(score + " . " + message);
300 }
301 }
302 },
303 undo: function(move) {
304 const navigate = !move;
305 if (navigate)
306 {
307 if (this.cursor < 0)
308 return; //no more moves
309 move = this.moves[this.cursor];
310 }
311 this.vr.undo(move);
312 this.cursor--;
313 this.lastMove = (this.cursor >= 0 ? this.moves[this.cursor] : undefined);
314 if (this.st.settings.sound == 2)
315 new Audio("/sounds/undo.mp3").play().catch(err => {});
316 this.incheck = this.vr.getCheckSquares(this.vr.turn);
317 if (!navigate)
318 this.moves.pop();
319 },
320 gotoMove: function(index) {
321 this.vr.re_init(this.moves[index].fen);
322 this.cursor = index;
323 this.lastMove = this.moves[index];
324 },
325 gotoBegin: function() {
326 this.vr.re_init(this.game.fenStart);
327 this.cursor = -1;
328 this.lastMove = null;
329 },
330 gotoEnd: function() {
331 this.gotoMove(this.moves.length-1);
332 },
333 flip: function() {
334 this.orientation = V.GetNextCol(this.orientation);
335 },
336 },
337 };
338 </script>