Styling, adjustments
[vchess.git] / client / src / components / BaseGame.vue
CommitLineData
a6088c90 1<template lang="pug">
9ca1e26b 2div#baseGame(tabindex=-1 @click="() => focusBg()" @keydown="handleKeys")
7e355d68
BA
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 }}
7aa548e7 8 .row
72ccbd67 9 #boardContainer.col-sm-12.col-md-9
7aa548e7
BA
10 Board(:vr="vr" :last-move="lastMove" :analyze="analyze"
11 :user-color="game.mycolor" :orientation="orientation"
12 :vname="game.vname" @play-move="play")
72ccbd67 13 #controls
9ca1e26b
BA
14 button(@click="gotoBegin") <<
15 button(@click="() => undo()") <
16 button(@click="flip") &#8645;
17 button(@click="() => play()") >
18 button(@click="gotoEnd") >>
7aa548e7 19 #fenDiv(v-if="showFen && !!vr")
603b8a8b 20 p(@click="gotoFenContent") {{ vr.getFen() }}
7aa548e7
BA
21 #pgnDiv
22 a#download(href="#")
23 button(@click="download") {{ st.tr["Download PGN"] }}
72ccbd67 24 .col-sm-12.col-md-3
7aa548e7
BA
25 MoveList(v-if="showMoves"
26 :moves="moves" :cursor="cursor" @goto-move="gotoMove")
a6088c90
BA
27</template>
28
29<script>
30import Board from "@/components/Board.vue";
f21cd6d9 31import MoveList from "@/components/MoveList.vue";
a6088c90
BA
32import { store } from "@/store";
33import { getSquareId } from "@/utils/squareId";
d4036efe 34import { getDate } from "@/utils/datetime";
a6088c90
BA
35
36export default {
37 name: 'my-base-game',
38 components: {
39 Board,
f21cd6d9 40 MoveList,
a6088c90 41 },
bc8734ba 42 // "vr": VariantRules object, describing the game state + rules
834c202a 43 props: ["vr","game"],
a6088c90
BA
44 data: function() {
45 return {
46 st: store.state,
b7c32f1a 47 // NOTE: all following variables must be reset at the beginning of a game
a6088c90
BA
48 endgameMessage: "",
49 orientation: "w",
50 score: "*", //'*' means 'unfinished'
b7c32f1a 51 moves: [],
a6088c90
BA
52 cursor: -1, //index of the move just played
53 lastMove: null,
06e79b07 54 gameHasEnded: false, //to avoid showing end message twice
a6088c90
BA
55 };
56 },
37cdcbf3 57 watch: {
834c202a
BA
58 // game initial FEN changes when a new game starts
59 "game.fenStart": function() {
4b0384fa 60 this.re_setVariables();
37cdcbf3 61 },
7e355d68
BA
62 // Received a new move to play:
63 "game.moveToPlay": function() {
64 this.play(this.game.moveToPlay, "receive", this.game.vname=="Dark");
65 },
52a8ab55 66 "game.score": function(score) {
06e79b07
BA
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 }
41cb9b94 72 },
37cdcbf3 73 },
a6088c90
BA
74 computed: {
75 showMoves: function() {
76 return true;
77 //return window.innerWidth >= 768;
78 },
79 showFen: function() {
834c202a
BA
80 return this.game.vname != "Dark" || this.score != "*";
81 },
82 analyze: function() {
41cb9b94 83 return this.game.mode == "analyze" || this.score != "*";
a6088c90
BA
84 },
85 },
4b0384fa
BA
86 created: function() {
87 if (!!this.game.fenStart)
88 this.re_setVariables();
89 },
a6088c90 90 methods: {
9ca1e26b
BA
91 focusBg: function() {
92 // TODO: small blue border appears...
93 document.getElementById("baseGame").focus();
94 },
95 handleKeys: function(e) {
5701c228
BA
96 if ([32,37,38,39,40].includes(e.keyCode))
97 e.preventDefault();
9ca1e26b
BA
98 switch (e.keyCode)
99 {
100 case 37:
101 this.undo();
102 break;
103 case 39:
104 this.play();
105 break;
5701c228 106 case 38:
9ca1e26b
BA
107 this.gotoBegin();
108 break;
109 case 40:
110 this.gotoEnd();
111 break;
112 case 32:
9ca1e26b
BA
113 this.flip();
114 break;
115 }
116 },
4b0384fa
BA
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 "*")
06e79b07 121 this.gameHasEnded = (this.score != "*");
4b0384fa 122 this.moves = JSON.parse(JSON.stringify(this.game.moves || []));
d4036efe
BA
123 // Post-processing: decorate each move with color + current FEN:
124 // (to be able to jump to any position quickly)
27d18a24 125 let vr_tmp = new V(this.game.fenStart); //vr is already at end of game
d4036efe
BA
126 this.moves.forEach(move => {
127 // NOTE: this is doing manually what play() function below achieve,
128 // but in a lighter "fast-forward" way
27d18a24
BA
129 move.color = vr_tmp.turn;
130 move.notation = vr_tmp.getNotation(move);
131 vr_tmp.play(move);
132 move.fen = vr_tmp.getFen();
d4036efe 133 });
697ee580
BA
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 }
4b0384fa
BA
140 const L = this.moves.length;
141 this.cursor = L-1;
142 this.lastMove = (L > 0 ? this.moves[L-1] : null);
143 },
603b8a8b
BA
144 gotoFenContent: function(event) {
145 this.$router.push("/analyze/" + this.game.vname +
146 "/?fen=" + event.target.innerText.replace(/ /g, "_"));
147 },
a6088c90
BA
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';
834c202a 159 pgn += '[Variant "' + this.game.vname + '"]\n';
a6088c90 160 pgn += '[Date "' + getDate(new Date()) + '"]\n';
d4036efe
BA
161 pgn += '[White "' + this.game.players[0].name + '"]\n';
162 pgn += '[Black "' + this.game.players[1].name + '"]\n';
834c202a 163 pgn += '[Fen "' + this.game.fenStart + '"]\n';
a6088c90
BA
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)
d4036efe 174 move += this.moves[i++].notation + ",";
a6088c90 175 move = move.slice(0,-1); //remove last comma
d4036efe 176 pgn += move + (i < this.moves.length ? " " : "");
a6088c90
BA
177 }
178 }
179 return pgn + "\n";
180 },
b988c726
BA
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;
4494c17c 202 let modalBox = document.getElementById("modalEog");
a6088c90
BA
203 modalBox.checked = true;
204 setTimeout(() => { modalBox.checked = false; }, 2000);
205 },
06e79b07
BA
206 endGame: function(score, message, bubbleUp) {
207 this.gameHasEnded = true;
a6088c90 208 this.score = score;
b988c726
BA
209 if (!message)
210 message = this.getScoreMessage(score);
211 this.showEndgameMsg(score + " . " + message);
06e79b07
BA
212 if (bubbleUp)
213 this.$emit("gameover", score);
a6088c90
BA
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 },
c4f91d3f 243 play: function(move, receive, noanimate) {
9d54ab89 244 const navigate = !move;
a6088c90
BA
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)
c4f91d3f 247 if (!navigate && !this.analyze && !receive
a6088c90
BA
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 }
c4f91d3f 258 if (!!receive && !noanimate) //opponent move, variant != "Dark"
a6088c90
BA
259 {
260 if (this.cursor < this.moves.length-1)
261 this.gotoEnd(); //required to play the move
262 return this.animateMove(move);
263 }
c4f91d3f
BA
264 if (!navigate)
265 {
266 move.color = this.vr.turn;
267 move.notation = this.vr.getNotation(move);
268 }
a6088c90 269 // Not programmatic, or animation is over
a6088c90
BA
270 this.vr.play(move);
271 this.cursor++;
272 this.lastMove = move;
a6088c90
BA
273 if (this.st.settings.sound == 2)
274 new Audio("/sounds/move.mp3").play().catch(err => {});
9d54ab89 275 if (!navigate)
a6088c90 276 {
9d54ab89
BA
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 }
a6088c90 286 }
f41ce580
BA
287 if (!this.analyze)
288 this.$emit("newmove", move); //post-processing (e.g. computer play)
d18bfa12 289 // Is opponent in check?
a6088c90
BA
290 this.incheck = this.vr.getCheckSquares(this.vr.turn);
291 const score = this.vr.getCurrentScore();
d18bfa12 292 if (score != "*")
a6088c90
BA
293 {
294 if (!this.analyze)
06e79b07 295 this.endGame(score, undefined, true);
b988c726
BA
296 else
297 {
298 // Just show score on screen (allow undo)
299 const message = this.getScoreMessage(score);
300 this.showEndgameMsg(score + " . " + message);
301 }
a6088c90 302 }
a6088c90
BA
303 },
304 undo: function(move) {
9d54ab89 305 const navigate = !move;
a6088c90
BA
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);
4494c17c 318 if (!navigate)
a6088c90
BA
319 this.moves.pop();
320 },
321 gotoMove: function(index) {
37cdcbf3 322 this.vr.re_init(this.moves[index].fen);
a6088c90
BA
323 this.cursor = index;
324 this.lastMove = this.moves[index];
325 },
326 gotoBegin: function() {
834c202a 327 this.vr.re_init(this.game.fenStart);
5701c228
BA
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 }
a6088c90
BA
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>
72ccbd67
BA
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>