Issue with observer in live games: moveToPlay repeated, no online indics ?!
[vchess.git] / client / src / components / BaseGame.vue
CommitLineData
a6088c90 1<template lang="pug">
dcd68c41
BA
2div#baseGame(tabindex=-1 @click="() => focusBg()"
3 @keydown="handleKeys" @wheel="handleScroll")
7e355d68 4 input#modalEog.modal(type="checkbox")
dcd68c41 5 div(role="dialog" data-checkbox="modalEog" aria-labelledby="eogMessage")
7e355d68
BA
6 .card.smallpad.small-modal.text-center
7 label.modal-close(for="modalEog")
8 h3#eogMessage.section {{ endgameMessage }}
cf94b843
BA
9 #gameContainer
10 #boardContainer
4f518610 11 Board(:vr="vr" :last-move="lastMove" :analyze="analyze"
cf94b843
BA
12 :user-color="game.mycolor" :orientation="orientation"
13 :vname="game.vname" @play-move="play")
4f518610 14 #turnIndicator(v-if="game.vname=='Dark' && game.score=='*'")
0e16cb26 15 | {{ turn }}
cf94b843
BA
16 #controls
17 button(@click="gotoBegin") <<
18 button(@click="() => undo()") <
19 button(@click="flip") &#8645;
20 button(@click="() => play()") >
21 button(@click="gotoEnd") >>
22 #pgnDiv
4f518610
BA
23 div(v-if="game.vname!='Dark' || game.score!='*'")
24 a#download(href="#")
25 button(@click="download") {{ st.tr["Download PGN"] }}
0e16cb26
BA
26 button(v-if="game.vname!='Dark' && game.mode!='analyze'"
27 @click="analyzePosition")
cf94b843 28 | {{ st.tr["Analyze"] }}
4f518610
BA
29 // NOTE: rather ugly hack to avoid showing twice "rules" link...
30 button(v-if="!$route.path.match('/variants/')" @click="showRules")
31 | {{ st.tr["Rules"] }}
cf94b843 32 #movesList
430a2038 33 MoveList(v-if="showMoves" :score="game.score" :message="game.scoreMsg"
5157ce0b
BA
34 :firstNum="firstMoveNumber" :moves="moves" :cursor="cursor"
35 @goto-move="gotoMove")
41c80bb6 36 .clearer
a6088c90
BA
37</template>
38
39<script>
40import Board from "@/components/Board.vue";
f21cd6d9 41import MoveList from "@/components/MoveList.vue";
a6088c90
BA
42import { store } from "@/store";
43import { getSquareId } from "@/utils/squareId";
d4036efe 44import { getDate } from "@/utils/datetime";
a6088c90
BA
45
46export default {
47 name: 'my-base-game',
48 components: {
49 Board,
f21cd6d9 50 MoveList,
a6088c90 51 },
bc8734ba 52 // "vr": VariantRules object, describing the game state + rules
834c202a 53 props: ["vr","game"],
a6088c90
BA
54 data: function() {
55 return {
56 st: store.state,
b7c32f1a 57 // NOTE: all following variables must be reset at the beginning of a game
a6088c90
BA
58 endgameMessage: "",
59 orientation: "w",
60 score: "*", //'*' means 'unfinished'
b7c32f1a 61 moves: [],
a6088c90
BA
62 cursor: -1, //index of the move just played
63 lastMove: null,
5157ce0b 64 firstMoveNumber: 0, //for printing
a6088c90
BA
65 };
66 },
37cdcbf3 67 watch: {
834c202a
BA
68 // game initial FEN changes when a new game starts
69 "game.fenStart": function() {
4b0384fa 70 this.re_setVariables();
37cdcbf3 71 },
7e355d68 72 // Received a new move to play:
63ca2b89 73 "game.moveToPlay": function(newMove) {
5bcc9b31
BA
74
75console.log(newMove);
76
63ca2b89
BA
77 if (!!newMove) //if stop + launch new game, get undefined move
78 this.play(newMove, "receive");
7e355d68 79 },
37cdcbf3 80 },
a6088c90
BA
81 computed: {
82 showMoves: function() {
4f518610 83 return this.game.vname != "Dark" || this.game.score != "*";
a6088c90 84 },
0e16cb26
BA
85 turn: function() {
86 let color = "";
87 const L = this.moves.length;
88 if (L == 0 || this.moves[L-1].color == "b")
89 color = "White";
90 else //if (this.moves[L-1].color == "w")
91 color = "Black";
92 return color + " turn";
93 },
4f518610
BA
94 analyze: function() {
95 return this.game.mode=="analyze" ||
96 // From Board viewpoint, a finished Dark game == analyze (TODO: unclear)
97 (this.game.vname == "Dark" && this.game.score != "*");
98 },
a6088c90 99 },
4b0384fa
BA
100 created: function() {
101 if (!!this.game.fenStart)
102 this.re_setVariables();
103 },
cf94b843 104 mounted: function() {
96e9585a
BA
105 // Take full width on small screens:
106 let boardSize = parseInt(localStorage.getItem("boardSize"));
107 if (!boardSize)
108 {
109 boardSize = (window.innerWidth >= 768
110 ? Math.min(600, 0.5*window.innerWidth) //heuristic...
111 : window.innerWidth);
112 }
113 const movesWidth = (window.innerWidth >= 768 ? 280 : 0);
114 document.getElementById("boardContainer").style.width = boardSize + "px";
115 let gameContainer = document.getElementById("gameContainer");
116 gameContainer.style.width = (boardSize + movesWidth) + "px";
cf94b843 117 },
a6088c90 118 methods: {
9ca1e26b 119 focusBg: function() {
41c80bb6 120 // NOTE: small blue border appears...
9ca1e26b
BA
121 document.getElementById("baseGame").focus();
122 },
123 handleKeys: function(e) {
5701c228
BA
124 if ([32,37,38,39,40].includes(e.keyCode))
125 e.preventDefault();
9ca1e26b
BA
126 switch (e.keyCode)
127 {
128 case 37:
129 this.undo();
130 break;
131 case 39:
132 this.play();
133 break;
5701c228 134 case 38:
9ca1e26b
BA
135 this.gotoBegin();
136 break;
137 case 40:
138 this.gotoEnd();
139 break;
140 case 32:
9ca1e26b
BA
141 this.flip();
142 break;
143 }
144 },
dcd68c41 145 handleScroll: function(e) {
4f518610
BA
146 // NOTE: since game.mode=="analyze" => no score, next condition is enough
147 if (this.game.score != "*")
41c80bb6
BA
148 {
149 e.preventDefault();
150 if (e.deltaY < 0)
151 this.undo();
152 else if (e.deltaY > 0)
153 this.play();
154 }
dcd68c41 155 },
0e16cb26
BA
156 showRules: function() {
157 //this.$router.push("/variants/" + this.game.vname);
158 window.open("#/variants/" + this.game.vname, "_blank"); //better
159 },
4b0384fa
BA
160 re_setVariables: function() {
161 this.endgameMessage = "";
162 this.orientation = this.game.mycolor || "w"; //default orientation for observed games
4b0384fa 163 this.moves = JSON.parse(JSON.stringify(this.game.moves || []));
d4036efe
BA
164 // Post-processing: decorate each move with color + current FEN:
165 // (to be able to jump to any position quickly)
27d18a24 166 let vr_tmp = new V(this.game.fenStart); //vr is already at end of game
5157ce0b
BA
167 this.firstMoveNumber =
168 Math.floor(V.ParseFen(this.game.fenStart).movesCount / 2);
d4036efe
BA
169 this.moves.forEach(move => {
170 // NOTE: this is doing manually what play() function below achieve,
171 // but in a lighter "fast-forward" way
27d18a24
BA
172 move.color = vr_tmp.turn;
173 move.notation = vr_tmp.getNotation(move);
174 vr_tmp.play(move);
175 move.fen = vr_tmp.getFen();
d4036efe 176 });
697ee580
BA
177 if (this.game.fenStart.indexOf(" b ") >= 0 ||
178 (this.moves.length > 0 && this.moves[0].color == "b"))
179 {
180 // 'end' is required for Board component to check lastMove for e.p.
181 this.moves.unshift({color: "w", notation: "...", end: {x:-1,y:-1}});
182 }
4b0384fa
BA
183 const L = this.moves.length;
184 this.cursor = L-1;
185 this.lastMove = (L > 0 ? this.moves[L-1] : null);
186 },
63ca2b89
BA
187 analyzePosition: function() {
188 const newUrl = "/analyze/" + this.game.vname +
189 "/?fen=" + this.vr.getFen().replace(/ /g, "_");
0e16cb26
BA
190 if (this.game.type == "live")
191 this.$router.push(newUrl); //open in same tab: against cheating...
192 else
193 window.open("#" + newUrl); //open in a new tab: more comfortable
603b8a8b 194 },
a6088c90
BA
195 download: function() {
196 const content = this.getPgn();
197 // Prepare and trigger download link
198 let downloadAnchor = document.getElementById("download");
199 downloadAnchor.setAttribute("download", "game.pgn");
200 downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
201 downloadAnchor.click();
202 },
203 getPgn: function() {
204 let pgn = "";
205 pgn += '[Site "vchess.club"]\n';
834c202a 206 pgn += '[Variant "' + this.game.vname + '"]\n';
a6088c90 207 pgn += '[Date "' + getDate(new Date()) + '"]\n';
d4036efe
BA
208 pgn += '[White "' + this.game.players[0].name + '"]\n';
209 pgn += '[Black "' + this.game.players[1].name + '"]\n';
834c202a 210 pgn += '[Fen "' + this.game.fenStart + '"]\n';
430a2038 211 pgn += '[Result "' + this.game.score + '"]\n\n';
a6088c90
BA
212 let counter = 1;
213 let i = 0;
214 while (i < this.moves.length)
215 {
216 pgn += (counter++) + ".";
217 for (let color of ["w","b"])
218 {
219 let move = "";
220 while (i < this.moves.length && this.moves[i].color == color)
d4036efe 221 move += this.moves[i++].notation + ",";
a6088c90 222 move = move.slice(0,-1); //remove last comma
d4036efe 223 pgn += move + (i < this.moves.length ? " " : "");
a6088c90
BA
224 }
225 }
226 return pgn + "\n";
227 },
b988c726
BA
228 getScoreMessage: function(score) {
229 let eogMessage = "Undefined";
230 switch (score)
231 {
232 case "1-0":
233 eogMessage = this.st.tr["White win"];
234 break;
235 case "0-1":
236 eogMessage = this.st.tr["Black win"];
237 break;
238 case "1/2":
239 eogMessage = this.st.tr["Draw"];
240 break;
241 case "?":
242 eogMessage = this.st.tr["Unfinished"];
243 break;
244 }
245 return eogMessage;
246 },
247 showEndgameMsg: function(message) {
248 this.endgameMessage = message;
4494c17c 249 let modalBox = document.getElementById("modalEog");
a6088c90
BA
250 modalBox.checked = true;
251 setTimeout(() => { modalBox.checked = false; }, 2000);
252 },
63ca2b89 253 animateMove: function(move, callback) {
a6088c90
BA
254 let startSquare = document.getElementById(getSquareId(move.start));
255 let endSquare = document.getElementById(getSquareId(move.end));
256 let rectStart = startSquare.getBoundingClientRect();
257 let rectEnd = endSquare.getBoundingClientRect();
258 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
259 let movingPiece =
260 document.querySelector("#" + getSquareId(move.start) + " > img.piece");
261 // HACK for animation (with positive translate, image slides "under background")
262 // Possible improvement: just alter squares on the piece's way...
263 const squares = document.getElementsByClassName("board");
264 for (let i=0; i<squares.length; i++)
265 {
266 let square = squares.item(i);
267 if (square.id != getSquareId(move.start))
268 square.style.zIndex = "-1";
269 }
270 movingPiece.style.transform = "translate(" + translation.x + "px," +
271 translation.y + "px)";
272 movingPiece.style.transitionDuration = "0.2s";
273 movingPiece.style.zIndex = "3000";
274 setTimeout( () => {
275 for (let i=0; i<squares.length; i++)
276 squares.item(i).style.zIndex = "auto";
277 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
63ca2b89 278 callback();
a6088c90
BA
279 }, 250);
280 },
63ca2b89
BA
281 play: function(move, receive) {
282 // NOTE: navigate and receive are mutually exclusive
9d54ab89 283 const navigate = !move;
63ca2b89
BA
284 // Forbid playing outside analyze mode, except if move is received.
285 // Sufficient condition because Board already knows which turn it is.
286 if (!navigate && this.game.mode!="analyze" && !receive
4f518610 287 && (this.game.score != "*" || this.cursor < this.moves.length-1))
a6088c90
BA
288 {
289 return;
290 }
63ca2b89
BA
291 const doPlayMove = () => {
292 if (!!receive && this.cursor < this.moves.length-1)
a6088c90 293 this.gotoEnd(); //required to play the move
63ca2b89
BA
294 if (navigate)
295 {
296 if (this.cursor == this.moves.length-1)
297 return; //no more moves
298 move = this.moves[this.cursor+1];
299 }
300 else
9d54ab89 301 {
63ca2b89
BA
302 move.color = this.vr.turn;
303 move.notation = this.vr.getNotation(move);
304 }
305 this.vr.play(move);
306 this.cursor++;
307 this.lastMove = move;
308 if (this.st.settings.sound == 2)
309 new Audio("/sounds/move.mp3").play().catch(err => {});
310 if (!navigate)
311 {
312 move.fen = this.vr.getFen();
9d54ab89
BA
313 // Stack move on movesList at current cursor
314 if (this.cursor == this.moves.length)
315 this.moves.push(move);
316 else
317 this.moves = this.moves.slice(0,this.cursor).concat([move]);
318 }
63ca2b89
BA
319 // Is opponent in check?
320 this.incheck = this.vr.getCheckSquares(this.vr.turn);
321 const score = this.vr.getCurrentScore();
322 if (score != "*")
323 {
324 const message = this.getScoreMessage(score);
325 if (this.game.mode != "analyze")
326 this.$emit("gameover", score, message);
327 else //just show score on screen (allow undo)
328 this.showEndgameMsg(score + " . " + message);
329 }
4f518610
BA
330 if (!navigate && this.game.mode!="analyze")
331 this.$emit("newmove", move); //post-processing (e.g. computer play)
63ca2b89
BA
332 };
333 if (!!receive && this.game.vname != "Dark")
334 this.animateMove(move, doPlayMove);
335 else
336 doPlayMove();
a6088c90
BA
337 },
338 undo: function(move) {
9d54ab89 339 const navigate = !move;
a6088c90
BA
340 if (navigate)
341 {
342 if (this.cursor < 0)
343 return; //no more moves
344 move = this.moves[this.cursor];
345 }
346 this.vr.undo(move);
347 this.cursor--;
348 this.lastMove = (this.cursor >= 0 ? this.moves[this.cursor] : undefined);
349 if (this.st.settings.sound == 2)
350 new Audio("/sounds/undo.mp3").play().catch(err => {});
351 this.incheck = this.vr.getCheckSquares(this.vr.turn);
4494c17c 352 if (!navigate)
a6088c90
BA
353 this.moves.pop();
354 },
355 gotoMove: function(index) {
37cdcbf3 356 this.vr.re_init(this.moves[index].fen);
a6088c90
BA
357 this.cursor = index;
358 this.lastMove = this.moves[index];
359 },
360 gotoBegin: function() {
5157ce0b
BA
361 if (this.cursor == -1)
362 return;
834c202a 363 this.vr.re_init(this.game.fenStart);
5701c228
BA
364 if (this.moves.length > 0 && this.moves[0].notation == "...")
365 {
366 this.cursor = 0;
367 this.lastMove = this.moves[0];
368 }
369 else
370 {
371 this.cursor = -1;
372 this.lastMove = null;
373 }
a6088c90
BA
374 },
375 gotoEnd: function() {
5157ce0b
BA
376 if (this.cursor == this.moves.length - 1)
377 return;
a6088c90
BA
378 this.gotoMove(this.moves.length-1);
379 },
380 flip: function() {
0e16cb26 381 this.orientation = V.GetOppCol(this.orientation);
a6088c90
BA
382 },
383 },
384};
385</script>
72ccbd67 386
41c80bb6 387<style lang="sass" scoped>
cf94b843
BA
388#baseGame
389 width: 100%
4f518610
BA
390 &:focus
391 outline: none
cf94b843
BA
392
393#gameContainer
72ccbd67
BA
394 margin-left: auto
395 margin-right: auto
cf94b843
BA
396
397#modal-eog+div .card
398 overflow: hidden
72ccbd67
BA
399#controls
400 margin-top: 10px
cf94b843
BA
401 margin-left: auto
402 margin-right: auto
72ccbd67
BA
403 button
404 display: inline-block
405 width: 20%
406 margin: 0
41c80bb6
BA
407@media screen and (min-width: 768px)
408 #controls
409 max-width: 400px
0e16cb26
BA
410#turnIndicator
411 text-align: center
cf94b843
BA
412#pgnDiv
413 text-align: center
414 margin-left: auto
415 margin-right: auto
72ccbd67 416#boardContainer
cf94b843 417 float: left
41c80bb6
BA
418// TODO: later, maybe, allow movesList of variable width
419// or e.g. between 250 and 350px (but more complicated)
cf94b843
BA
420#movesList
421 width: 280px
422 float: left
96e9585a
BA
423@media screen and (max-width: 767px)
424 #movesList
425 width: 100%
426 float: none
427 clear: both
72ccbd67 428</style>