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