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