Update TODO
[vchess.git] / client / src / components / BaseGame.vue
CommitLineData
a6088c90 1<template lang="pug">
e71161fb 2div#baseGame
7e355d68 3 input#modalEog.modal(type="checkbox")
6808d7a1
BA
4 div#eogDiv(
5 role="dialog"
6 data-checkbox="modalEog"
7 )
9a3049f3 8 .card.text-center
7e355d68 9 label.modal-close(for="modalEog")
9a3049f3 10 h3.section {{ endgameMessage }}
cf94b843
BA
11 #gameContainer
12 #boardContainer
6808d7a1
BA
13 Board(
14 :vr="vr"
15 :last-move="lastMove"
20620465
BA
16 :analyze="game.mode=='analyze'"
17 :score="game.score"
6808d7a1
BA
18 :user-color="game.mycolor"
19 :orientation="orientation"
20 :vname="game.vname"
21 :incheck="incheck"
22 @play-move="play"
23 )
20620465 24 #turnIndicator(v-if="showTurn") {{ turn }}
cf94b843 25 #controls
9ddaf8da
BA
26 button(@click="gotoBegin()") <<
27 button(@click="undo()") <
71ef1664 28 button(v-if="canFlip" @click="flip()") &#8645;
9ddaf8da
BA
29 button(@click="play()") >
30 button(@click="gotoEnd()") >>
bd76b456 31 #belowControls
20620465 32 #downloadDiv(v-if="allowDownloadPGN")
4f518610 33 a#download(href="#")
9ddaf8da 34 button(@click="download()") {{ st.tr["Download"] }} PGN
6808d7a1 35 button(
20620465 36 v-if="canAnalyze"
6808d7a1
BA
37 @click="analyzePosition()"
38 )
677fe285 39 | {{ st.tr["Analyse"] }}
20620465 40 // NOTE: variants pages already have a "Rules" link on top
6808d7a1
BA
41 button(
42 v-if="!$route.path.match('/variants/')"
43 @click="showRules()"
44 )
4f518610 45 | {{ st.tr["Rules"] }}
cf94b843 46 #movesList
6808d7a1 47 MoveList(
933fd1f9 48 :show="showMoves"
6808d7a1
BA
49 :score="game.score"
50 :message="game.scoreMsg"
51 :firstNum="firstMoveNumber"
52 :moves="moves"
53 :cursor="cursor"
54 @goto-move="gotoMove"
55 )
41c80bb6 56 .clearer
a6088c90
BA
57</template>
58
59<script>
60import Board from "@/components/Board.vue";
f21cd6d9 61import MoveList from "@/components/MoveList.vue";
a6088c90
BA
62import { store } from "@/store";
63import { getSquareId } from "@/utils/squareId";
d4036efe 64import { getDate } from "@/utils/datetime";
602d6bef 65import { processModalClick } from "@/utils/modalClick";
77c50966 66import { getScoreMessage } from "@/utils/scoring";
e71161fb
BA
67import { getFullNotation } from "@/utils/notation";
68import { undoMove } from "@/utils/playUndo";
a6088c90 69export default {
6808d7a1 70 name: "my-base-game",
a6088c90
BA
71 components: {
72 Board,
6808d7a1 73 MoveList
a6088c90 74 },
e71161fb 75 props: ["game"],
a6088c90
BA
76 data: function() {
77 return {
78 st: store.state,
b7c32f1a 79 // NOTE: all following variables must be reset at the beginning of a game
e71161fb 80 vr: null, //VariantRules object, game state
a6088c90
BA
81 endgameMessage: "",
82 orientation: "w",
83 score: "*", //'*' means 'unfinished'
b7c32f1a 84 moves: [],
e71161fb 85 // TODO: later, use subCursor to navigate intra-multimoves?
a6088c90
BA
86 cursor: -1, //index of the move just played
87 lastMove: null,
5157ce0b 88 firstMoveNumber: 0, //for printing
e71161fb
BA
89 incheck: [], //for Board
90 inMultimove: false
a6088c90
BA
91 };
92 },
37cdcbf3 93 watch: {
834c202a
BA
94 // game initial FEN changes when a new game starts
95 "game.fenStart": function() {
4b0384fa 96 this.re_setVariables();
37cdcbf3
BA
97 },
98 },
a6088c90
BA
99 computed: {
100 showMoves: function() {
933fd1f9
BA
101 return this.game.score != "*"
102 ? "all"
103 : (this.vr ? this.vr.showMoves : "none");
20620465
BA
104 },
105 showTurn: function() {
71ef1664
BA
106 return (
107 this.game.score == '*' &&
108 this.vr &&
109 (this.vr.showMoves != "all" || !this.vr.canFlip)
110 );
a6088c90 111 },
58ae6be5 112 turn: function() {
71ef1664
BA
113 if (!this.vr)
114 return "";
115 if (this.vr.showMoves != "all")
116 return this.st.tr[(this.vr.turn == 'w' ? "White" : "Black") + " to move"]
117 // Cannot flip: racing king or circular chess
118 return this.vr.movesCount == 0 && this.game.mycolor == "w"
119 ? this.st.tr["It's your turn!"]
a13cbc0f 120 : "";
58ae6be5 121 },
20620465 122 canAnalyze: function() {
933fd1f9 123 return this.game.mode != "analyze" && this.vr && this.vr.canAnalyze;
20620465 124 },
71ef1664
BA
125 canFlip: function() {
126 return this.vr && this.vr.canFlip;
127 },
20620465 128 allowDownloadPGN: function() {
933fd1f9 129 return this.game.score != "*" || (this.vr && this.vr.showMoves == "all");
6808d7a1 130 }
a6088c90 131 },
4b0384fa 132 created: function() {
6808d7a1 133 if (this.game.fenStart) this.re_setVariables();
4b0384fa 134 },
cf94b843 135 mounted: function() {
e71161fb
BA
136 if (!("ontouchstart" in window)) {
137 // Desktop browser:
138 const baseGameDiv = document.getElementById("baseGame");
139 baseGameDiv.tabIndex = 0;
140 baseGameDiv.addEventListener("click", this.focusBg);
141 baseGameDiv.addEventListener("keydown", this.handleKeys);
142 baseGameDiv.addEventListener("wheel", this.handleScroll);
143 }
5b3dc10e
BA
144 document.getElementById("eogDiv").addEventListener(
145 "click",
146 processModalClick);
cf94b843 147 },
a6088c90 148 methods: {
9ca1e26b 149 focusBg: function() {
9ca1e26b
BA
150 document.getElementById("baseGame").focus();
151 },
152 handleKeys: function(e) {
6808d7a1
BA
153 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
154 switch (e.keyCode) {
9ca1e26b
BA
155 case 37:
156 this.undo();
157 break;
158 case 39:
159 this.play();
160 break;
5701c228 161 case 38:
9ca1e26b
BA
162 this.gotoBegin();
163 break;
164 case 40:
165 this.gotoEnd();
166 break;
167 case 32:
9ca1e26b
BA
168 this.flip();
169 break;
170 }
171 },
dcd68c41 172 handleScroll: function(e) {
e71161fb
BA
173 e.preventDefault();
174 if (e.deltaY < 0) this.undo();
175 else if (e.deltaY > 0) this.play();
dcd68c41 176 },
0e16cb26
BA
177 showRules: function() {
178 //this.$router.push("/variants/" + this.game.vname);
179 window.open("#/variants/" + this.game.vname, "_blank"); //better
180 },
4b0384fa
BA
181 re_setVariables: function() {
182 this.endgameMessage = "";
8477e53d
BA
183 // "w": default orientation for observed games
184 this.orientation = this.game.mycolor || "w";
4b0384fa 185 this.moves = JSON.parse(JSON.stringify(this.game.moves || []));
e71161fb
BA
186 // Post-processing: decorate each move with notation and FEN
187 this.vr = new V(this.game.fenStart);
8477e53d
BA
188 const parsedFen = V.ParseFen(this.game.fenStart);
189 const firstMoveColor = parsedFen.turn;
190 this.firstMoveNumber = Math.floor(parsedFen.movesCount / 2);
d4036efe 191 this.moves.forEach(move => {
e71161fb
BA
192 // Strategy working also for multi-moves:
193 if (!Array.isArray(move)) move = [move];
194 move.forEach(m => {
195 m.notation = this.vr.getNotation(m);
196 this.vr.play(m);
197 });
d4036efe 198 });
8477e53d 199 if (firstMoveColor == "b") {
311cba76 200 // 'start' & 'end' is required for Board component
6808d7a1 201 this.moves.unshift({
6808d7a1 202 notation: "...",
311cba76 203 start: { x: -1, y: -1 },
6808d7a1
BA
204 end: { x: -1, y: -1 }
205 });
697ee580 206 }
e71161fb 207 this.positionCursorTo(this.moves.length - 1);
9ef63965 208 this.incheck = this.vr.getCheckSquares(this.vr.turn);
4b0384fa 209 },
e71161fb
BA
210 positionCursorTo: function(index) {
211 this.cursor = index;
212 // Caution: last move in moves array might be a multi-move
213 if (index >= 0) {
214 if (Array.isArray(this.moves[index])) {
215 const L = this.moves[index].length;
216 this.lastMove = this.moves[index][L - 1];
217 } else {
218 this.lastMove = this.moves[index];
219 }
220 }
221 else
222 this.lastMove = null;
223 },
63ca2b89 224 analyzePosition: function() {
6808d7a1
BA
225 const newUrl =
226 "/analyse/" +
227 this.game.vname +
228 "/?fen=" +
229 this.vr.getFen().replace(/ /g, "_");
910d631b 230 // Open in same tab in live games (against cheating)
6808d7a1 231 if (this.game.type == "live") this.$router.push(newUrl);
910d631b 232 else window.open("#" + newUrl);
603b8a8b 233 },
a6088c90
BA
234 download: function() {
235 const content = this.getPgn();
236 // Prepare and trigger download link
237 let downloadAnchor = document.getElementById("download");
238 downloadAnchor.setAttribute("download", "game.pgn");
6808d7a1
BA
239 downloadAnchor.href =
240 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
a6088c90
BA
241 downloadAnchor.click();
242 },
243 getPgn: function() {
244 let pgn = "";
245 pgn += '[Site "vchess.club"]\n';
834c202a 246 pgn += '[Variant "' + this.game.vname + '"]\n';
a6088c90 247 pgn += '[Date "' + getDate(new Date()) + '"]\n';
d4036efe
BA
248 pgn += '[White "' + this.game.players[0].name + '"]\n';
249 pgn += '[Black "' + this.game.players[1].name + '"]\n';
834c202a 250 pgn += '[Fen "' + this.game.fenStart + '"]\n';
430a2038 251 pgn += '[Result "' + this.game.score + '"]\n\n';
e71161fb
BA
252 for (let i = 0; i < this.moves.length; i += 2) {
253 pgn += (i/2+1) + "." + getFullNotation(this.moves[i]) + " ";
254 if (i+1 < this.moves.length)
255 pgn += getFullNotation(this.moves[i+1]) + " ";
a6088c90
BA
256 }
257 return pgn + "\n";
258 },
b988c726
BA
259 showEndgameMsg: function(message) {
260 this.endgameMessage = message;
4494c17c 261 let modalBox = document.getElementById("modalEog");
a6088c90 262 modalBox.checked = true;
6808d7a1
BA
263 setTimeout(() => {
264 modalBox.checked = false;
265 }, 2000);
a6088c90 266 },
e71161fb 267 // Animate an elementary move
63ca2b89 268 animateMove: function(move, callback) {
a6088c90
BA
269 let startSquare = document.getElementById(getSquareId(move.start));
270 let endSquare = document.getElementById(getSquareId(move.end));
271 let rectStart = startSquare.getBoundingClientRect();
272 let rectEnd = endSquare.getBoundingClientRect();
6808d7a1
BA
273 let translation = {
274 x: rectEnd.x - rectStart.x,
275 y: rectEnd.y - rectStart.y
276 };
277 let movingPiece = document.querySelector(
278 "#" + getSquareId(move.start) + " > img.piece"
279 );
a6088c90
BA
280 // HACK for animation (with positive translate, image slides "under background")
281 // Possible improvement: just alter squares on the piece's way...
282 const squares = document.getElementsByClassName("board");
6808d7a1 283 for (let i = 0; i < squares.length; i++) {
a6088c90 284 let square = squares.item(i);
6808d7a1 285 if (square.id != getSquareId(move.start)) square.style.zIndex = "-1";
a6088c90 286 }
6808d7a1
BA
287 movingPiece.style.transform =
288 "translate(" + translation.x + "px," + translation.y + "px)";
910d631b 289 movingPiece.style.transitionDuration = "0.25s";
a6088c90 290 movingPiece.style.zIndex = "3000";
6808d7a1
BA
291 setTimeout(() => {
292 for (let i = 0; i < squares.length; i++)
a6088c90
BA
293 squares.item(i).style.zIndex = "auto";
294 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
63ca2b89 295 callback();
a6088c90
BA
296 }, 250);
297 },
8055eabd
BA
298 // For Analyse mode:
299 emitFenIfAnalyze: function() {
300 if (this.game.mode == "analyze") {
301 this.$emit(
302 "fenchange",
303 this.lastMove ? this.lastMove.fen : this.game.fenStart
304 );
305 }
306 },
e71161fb
BA
307 // "light": if gotoMove() or gotoEnd()
308 // data: some custom data (addTime) to be re-emitted
309 play: function(move, received, light, data) {
9d54ab89 310 const navigate = !move;
e71161fb
BA
311 const playSubmove = (smove) => {
312 if (!navigate) smove.notation = this.vr.getNotation(smove);
313 this.vr.play(smove);
314 this.lastMove = smove;
315 // Is opponent in check?
316 this.incheck = this.vr.getCheckSquares(this.vr.turn);
317 if (!navigate) {
318 if (!this.inMultimove) {
319 if (this.cursor < this.moves.length - 1)
8055eabd 320 this.moves = this.moves.slice(0, this.cursor + 1);
e71161fb
BA
321 this.moves.push(smove);
322 this.inMultimove = true; //potentially
323 this.cursor++;
324 } else {
325 // Already in the middle of a multi-move
326 const L = this.moves.length;
327 if (!Array.isArray(this.moves[L-1]))
328 this.$set(this.moves, L-1, [this.moves[L-1], smove]);
329 else
330 this.$set(this.moves, L-1, this.moves.concat([smove]));
331 }
332 }
333 };
334 const playMove = () => {
335 const animate = V.ShowMoves == "all" && received;
336 if (!Array.isArray(move)) move = [move];
337 let moveIdx = 0;
338 let self = this;
339 const initurn = this.vr.turn;
340 (function executeMove() {
341 const smove = move[moveIdx++];
342 if (animate) {
343 self.animateMove(smove, () => {
344 playSubmove(smove);
345 if (moveIdx < move.length)
346 setTimeout(executeMove, 500);
347 else afterMove(smove, initurn);
348 });
349 } else {
350 playSubmove(smove);
351 if (moveIdx < move.length) executeMove();
352 else afterMove(smove, initurn);
353 }
354 })();
355 };
356 const afterMove = (smove, initurn) => {
e71161fb
BA
357 if (this.vr.turn != initurn) {
358 // Turn has changed: move is complete
e891730f 359 if (!smove.fen) {
cc00b83c
BA
360 // NOTE: only FEN of last sub-move is required (thus setting it here)
361 smove.fen = this.vr.getFen();
e891730f
BA
362 this.emitFenIfAnalyze();
363 }
e71161fb
BA
364 this.inMultimove = false;
365 const score = this.vr.getCurrentScore();
366 if (score != "*") {
367 const message = getScoreMessage(score);
368 if (!navigate && this.game.mode != "analyze")
369 this.$emit("gameover", score, message);
e533e1ba
BA
370 else if (this.game.mode == "analyze")
371 // Just show score on screen (allow undo)
372 this.showEndgameMsg(score + " . " + this.st.tr[message]);
e71161fb
BA
373 }
374 if (!navigate && this.game.mode != "analyze") {
375 const L = this.moves.length;
376 // Post-processing (e.g. computer play)
377 this.$emit("newmove", this.moves[L-1], data);
378 }
379 }
380 };
381 // NOTE: navigate and received are mutually exclusive
382 if (navigate) {
383 // The move to navigate to is necessarily full:
384 if (this.cursor == this.moves.length - 1) return; //no more moves
385 move = this.moves[this.cursor + 1];
386 if (light) {
387 // Just play the move, nothing else:
388 if (!Array.isArray(move)) move = [move];
389 for (let i=0; i < move.length; i++) this.vr.play(move[i]);
390 }
8055eabd
BA
391 else {
392 playMove();
393 this.emitFenIfAnalyze();
394 }
e71161fb
BA
395 this.cursor++;
396 return;
397 }
63ca2b89
BA
398 // Forbid playing outside analyze mode, except if move is received.
399 // Sufficient condition because Board already knows which turn it is.
6808d7a1 400 if (
6808d7a1 401 this.game.mode != "analyze" &&
e71161fb 402 !received &&
6808d7a1
BA
403 (this.game.score != "*" || this.cursor < this.moves.length - 1)
404 ) {
a6088c90
BA
405 return;
406 }
e71161fb
BA
407 // To play a received move, cursor must be at the end of the game:
408 if (received && this.cursor < this.moves.length - 1)
409 this.gotoEnd();
410 playMove();
411 },
412 cancelCurrentMultimove: function() {
e71161fb
BA
413 const L = this.moves.length;
414 let move = this.moves[L-1];
415 if (!Array.isArray(move)) move = [move];
416 for (let i=move.length -1; i >= 0; i--) this.vr.undo(move[i]);
417 this.moves.pop();
418 this.cursor--;
419 this.inMultimove = false;
420 },
421 cancelLastMove: function() {
422 // The last played move was canceled (corr game)
423 this.undo();
424 this.moves.pop();
425 },
426 // "light": if gotoMove() or gotoBegin()
427 undo: function(move, light) {
428 if (this.inMultimove) {
429 this.cancelCurrentMultimove();
63ca2b89 430 this.incheck = this.vr.getCheckSquares(this.vr.turn);
e71161fb
BA
431 } else {
432 if (!move) {
433 if (this.cursor < 0) return; //no more moves
434 move = this.moves[this.cursor];
435 }
436 // Caution; if multi-move, undo all submoves from last to first
437 undoMove(move, this.vr);
438 if (light) this.cursor--;
439 else {
440 this.positionCursorTo(this.cursor - 1);
e71161fb 441 this.incheck = this.vr.getCheckSquares(this.vr.turn);
8055eabd 442 this.emitFenIfAnalyze();
63ca2b89 443 }
a6088c90 444 }
a6088c90
BA
445 },
446 gotoMove: function(index) {
e71161fb
BA
447 if (this.inMultimove) this.cancelCurrentMultimove();
448 if (index == this.cursor) return;
449 if (index < this.cursor) {
450 while (this.cursor > index)
451 this.undo(null, null, "light");
452 }
453 else {
454 // index > this.cursor)
455 while (this.cursor < index)
456 this.play(null, null, "light");
457 }
458 // NOTE: next line also re-assign cursor, but it's very light
459 this.positionCursorTo(index);
8b405c81 460 this.incheck = this.vr.getCheckSquares(this.vr.turn);
8055eabd 461 this.emitFenIfAnalyze();
a6088c90
BA
462 },
463 gotoBegin: function() {
e71161fb
BA
464 if (this.inMultimove) this.cancelCurrentMultimove();
465 while (this.cursor >= 0)
466 this.undo(null, null, "light");
6808d7a1 467 if (this.moves.length > 0 && this.moves[0].notation == "...") {
5701c228
BA
468 this.cursor = 0;
469 this.lastMove = this.moves[0];
6808d7a1 470 } else {
5701c228
BA
471 this.lastMove = null;
472 }
e71161fb 473 this.incheck = [];
8055eabd 474 this.emitFenIfAnalyze();
a6088c90
BA
475 },
476 gotoEnd: function() {
6808d7a1
BA
477 if (this.cursor == this.moves.length - 1) return;
478 this.gotoMove(this.moves.length - 1);
8055eabd 479 this.emitFenIfAnalyze();
a6088c90
BA
480 },
481 flip: function() {
0e16cb26 482 this.orientation = V.GetOppCol(this.orientation);
6808d7a1
BA
483 }
484 }
a6088c90
BA
485};
486</script>
72ccbd67 487
41c80bb6 488<style lang="sass" scoped>
9a3049f3
BA
489[type="checkbox"]#modalEog+div .card
490 min-height: 45px
910d631b 491
cf94b843
BA
492#baseGame
493 width: 100%
4f518610
BA
494 &:focus
495 outline: none
cf94b843
BA
496
497#gameContainer
72ccbd67
BA
498 margin-left: auto
499 margin-right: auto
cf94b843 500
ed06d9e9
BA
501#downloadDiv
502 display: inline-block
503
72ccbd67 504#controls
bd76b456 505 margin: 0 auto
71ef1664 506 text-align: center
72ccbd67
BA
507 button
508 display: inline-block
509 width: 20%
510 margin: 0
910d631b 511
0e16cb26
BA
512#turnIndicator
513 text-align: center
29bc61be 514 font-weight: bold
910d631b 515
bd76b456
BA
516#belowControls
517 border-top: 1px solid #2f4f4f
cf94b843 518 text-align: center
bd76b456
BA
519 margin: 0 auto
520 & > #downloadDiv
521 margin: 0
522 & > button
523 margin: 0
524 & > button
525 border-left: 1px solid #2f4f4f
526 margin: 0
910d631b 527
72ccbd67 528#boardContainer
cf94b843 529 float: left
41c80bb6
BA
530// TODO: later, maybe, allow movesList of variable width
531// or e.g. between 250 and 350px (but more complicated)
910d631b 532
cf94b843
BA
533#movesList
534 width: 280px
535 float: left
910d631b 536
96e9585a
BA
537@media screen and (max-width: 767px)
538 #movesList
539 width: 100%
540 float: none
541 clear: both
72ccbd67 542</style>