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