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