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