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