Improve display
[vchess.git] / client / src / components / Board.vue
1 <script>
2 import { getSquareId, getSquareFromId } from "@/utils/squareId";
3 import { ArrayFun } from "@/utils/array";
4 import { store } from "@/store";
5 export default {
6 name: "my-board",
7 // Last move cannot be guessed from here, and is required for highlights.
8 // vr: object to check moves, print board...
9 // userColor is left undefined for an external observer
10 props: [
11 "vr",
12 "lastMove",
13 "analyze",
14 "score",
15 "incheck",
16 "orientation",
17 "userColor",
18 "vname"
19 ],
20 data: function() {
21 return {
22 mobileBrowser: ("ontouchstart" in window),
23 possibleMoves: [], //filled after each valid click/dragstart
24 choices: [], //promotion pieces, or checkered captures... (as moves)
25 selectedPiece: null, //moving piece (or clicked piece)
26 start: null, //pixels coordinates + id of starting square (click or drag)
27 startArrow: null,
28 movingArrow: { x: -1, y: -1 },
29 arrows: [], //object of {start: x,y / end: x,y}
30 circles: {}, //object of squares' ID --> true (TODO: use a set?)
31 click: "",
32 clickTime: 0,
33 settings: store.state.settings
34 };
35 },
36 render(h) {
37 if (!this.vr) {
38 // Return empty div of class 'game' to avoid error when setting size
39 return h("div", {
40 class: {
41 game: true
42 }
43 });
44 }
45 const [sizeX, sizeY] = [V.size.x, V.size.y];
46 // Precompute hints squares to facilitate rendering
47 let hintSquares = ArrayFun.init(sizeX, sizeY, false);
48 this.possibleMoves.forEach(m => {
49 hintSquares[m.end.x][m.end.y] = true;
50 });
51 // Also precompute in-check squares
52 let incheckSq = ArrayFun.init(sizeX, sizeY, false);
53 this.incheck.forEach(sq => {
54 incheckSq[sq[0]][sq[1]] = true;
55 });
56
57 const lm = this.lastMove;
58 const showLight = (
59 this.settings.highlight &&
60 ["all","highlight"].includes(V.ShowMoves)
61 );
62 const showCheck = (
63 this.settings.highlight &&
64 ["all","highlight","byrow"].includes(V.ShowMoves)
65 );
66 const orientation = !V.CanFlip ? "w" : this.orientation;
67 // Ensure that squares colors do not change when board is flipped
68 const lightSquareMod = (sizeX + sizeY) % 2;
69 const showPiece = (x, y) => {
70 return (
71 this.vr.board[x][y] != V.EMPTY &&
72 (!this.vr.enlightened || this.analyze || this.score != "*" ||
73 (!!this.userColor && this.vr.enlightened[this.userColor][x][y]))
74 );
75 };
76 const inHighlight = (x, y) => {
77 return showLight && !!lm && (
78 (lm.end.x == x && lm.end.y == y) ||
79 (lm.start.x == x && lm.start.y == y));
80 };
81 const inShadow = (x, y) => {
82 return (
83 !this.analyze &&
84 this.score == "*" &&
85 this.vr.enlightened &&
86 (!this.userColor || !this.vr.enlightened[this.userColor][x][y])
87 );
88 };
89 // Create board element (+ reserves if needed by variant)
90 let elementArray = [];
91 const gameDiv = h(
92 "div",
93 {
94 "class": {
95 game: true,
96 clearer: true
97 }
98 },
99 [...Array(sizeX).keys()].map(i => {
100 const ci = orientation == "w" ? i : sizeX - i - 1;
101 return h(
102 "div",
103 {
104 "class": {
105 row: true
106 },
107 style: { opacity: this.choices.length > 0 ? "0.5" : "1" }
108 },
109 [...Array(sizeY).keys()].map(j => {
110 const cj = orientation == "w" ? j : sizeY - j - 1;
111 const squareId = "sq-" + ci + "-" + cj;
112 let elems = [];
113 if (showPiece(ci, cj)) {
114 elems.push(
115 h("img", {
116 "class": {
117 piece: true,
118 ghost:
119 !!this.selectedPiece &&
120 this.selectedPiece.parentNode.id == squareId
121 },
122 attrs: {
123 src:
124 "/images/pieces/" +
125 this.vr.getPpath(
126 this.vr.board[ci][cj],
127 // Extra args useful for some variants:
128 this.userColor,
129 this.score,
130 this.orientation) +
131 V.IMAGE_EXTENSION
132 }
133 })
134 );
135 }
136 if (this.settings.hints && hintSquares[ci][cj]) {
137 elems.push(
138 h("img", {
139 "class": {
140 "mark-square": true
141 },
142 attrs: {
143 src: "/images/mark.svg"
144 }
145 })
146 );
147 }
148 if (!!this.circles[squareId]) {
149 elems.push(
150 h("img", {
151 "class": {
152 "circle-square": true
153 },
154 attrs: {
155 src: "/images/circle.svg"
156 }
157 })
158 );
159 }
160 const lightSquare = (ci + cj) % 2 == lightSquareMod;
161 return h(
162 "div",
163 {
164 "class": {
165 board: true,
166 ["board" + sizeY]: true,
167 "light-square": lightSquare,
168 "dark-square": !lightSquare,
169 [this.settings.bcolor]: true,
170 "in-shadow": inShadow(ci, cj),
171 "highlight-light": inHighlight(ci, cj) && lightSquare,
172 "highlight-dark": inHighlight(ci, cj) && !lightSquare,
173 "incheck-light":
174 showCheck && lightSquare && incheckSq[ci][cj],
175 "incheck-dark":
176 showCheck && !lightSquare && incheckSq[ci][cj]
177 },
178 attrs: {
179 id: getSquareId({ x: ci, y: cj })
180 }
181 },
182 elems
183 );
184 })
185 );
186 })
187 );
188 if (!!this.vr.reserve) {
189 const playingColor = this.userColor || "w"; //default for an observer
190 const shiftIdx = playingColor == "w" ? 0 : 1;
191 let myReservePiecesArray = [];
192 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
193 const qty = this.vr.reserve[playingColor][V.RESERVE_PIECES[i]];
194 myReservePiecesArray.push(
195 h(
196 "div",
197 {
198 "class": { board: true, ["board" + sizeY]: true },
199 attrs: { id: getSquareId({ x: sizeX + shiftIdx, y: i }) },
200 style: { opacity: qty > 0 ? 1 : 0.35 }
201 },
202 [
203 h("img", {
204 "class": { piece: true, reserve: true },
205 attrs: {
206 src:
207 "/images/pieces/" +
208 this.vr.getReservePpath(i, playingColor) +
209 ".svg"
210 }
211 }),
212 h("sup", { "class": { "reserve-count": true } }, [ qty ])
213 ]
214 )
215 );
216 }
217 let oppReservePiecesArray = [];
218 const oppCol = V.GetOppCol(playingColor);
219 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
220 const qty = this.vr.reserve[oppCol][V.RESERVE_PIECES[i]];
221 oppReservePiecesArray.push(
222 h(
223 "div",
224 {
225 "class": { board: true, ["board" + sizeY]: true },
226 attrs: { id: getSquareId({ x: sizeX + (1 - shiftIdx), y: i }) },
227 style: { opacity: qty > 0 ? 1 : 0.35 }
228 },
229 [
230 h("img", {
231 "class": { piece: true, reserve: true },
232 attrs: {
233 src:
234 "/images/pieces/" +
235 this.vr.getReservePpath(i, oppCol) +
236 ".svg"
237 }
238 }),
239 h("sup", { "class": { "reserve-count": true } }, [ qty ])
240 ]
241 )
242 );
243 }
244 const myReserveTop = (
245 (playingColor == 'w' && orientation == 'b') ||
246 (playingColor == 'b' && orientation == 'w')
247 );
248 // Center reserves, assuming same number of pieces for each side:
249 const nbReservePieces = myReservePiecesArray.length;
250 const marginLeft = ((100 - nbReservePieces * (100 / sizeY)) / 2) + "%";
251 const reserveTop =
252 h(
253 "div",
254 {
255 "class": {
256 game: true,
257 "reserve-div": true
258 },
259 style: {
260 "margin-left": marginLeft
261 }
262 },
263 [
264 h(
265 "div",
266 {
267 "class": {
268 row: true,
269 "reserve-row": true
270 }
271 },
272 myReserveTop ? myReservePiecesArray : oppReservePiecesArray
273 )
274 ]
275 );
276 var reserveBottom =
277 h(
278 "div",
279 {
280 "class": {
281 game: true,
282 "reserve-div": true
283 },
284 style: {
285 "margin-left": marginLeft
286 }
287 },
288 [
289 h(
290 "div",
291 {
292 "class": {
293 row: true,
294 "reserve-row": true
295 }
296 },
297 myReserveTop ? oppReservePiecesArray : myReservePiecesArray
298 )
299 ]
300 );
301 elementArray.push(reserveTop);
302 }
303 elementArray.push(gameDiv);
304 if (!!this.vr.reserve) elementArray.push(reserveBottom);
305 const boardElt = document.querySelector(".game");
306 // boardElt might be undefine (at first drawing),
307 // but it won't be used in this case.
308 const squareWidth = (!!boardElt ? boardElt.offsetWidth / sizeY : 42);
309 if (this.choices.length > 0 && !!boardElt) {
310 // No choices to show at first drawing
311 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
312 const maxNbeltsPerRow = Math.min(this.choices.length, sizeY);
313 let topOffset = offset[0] + (sizeY / 2) * squareWidth - squareWidth / 2;
314 let choicesHeight = squareWidth;
315 if (this.choices.length >= sizeY) {
316 // A second row is required (Eightpieces variant)
317 topOffset -= squareWidth / 2;
318 choicesHeight *= 2;
319 }
320 const choices = h(
321 "div",
322 {
323 attrs: { id: "choices" },
324 "class": { row: true },
325 style: {
326 top: topOffset + "px",
327 left:
328 offset[1] +
329 (squareWidth * Math.max(sizeY - this.choices.length, 0)) / 2 +
330 "px",
331 width: (maxNbeltsPerRow * squareWidth) + "px",
332 height: choicesHeight + "px"
333 }
334 },
335 [ h(
336 "div",
337 {
338 "class": { "full-width": true }
339 },
340 this.choices.map(m => {
341 // A "choice" is a move
342 const applyMove = (e) => {
343 e.stopPropagation();
344 // Force a delay between move is shown and clicked
345 // (otherwise a "double-click" bug might occur)
346 if (Date.now() - this.clickTime < 200) return;
347 this.choices = [];
348 this.play(m);
349 };
350 const onClick =
351 this.mobileBrowser
352 ? { touchend: applyMove }
353 : { mouseup: applyMove };
354 return h(
355 "div",
356 {
357 "class": {
358 board: true,
359 ["board" + sizeY]: true
360 },
361 style: {
362 width: (100 / maxNbeltsPerRow) + "%",
363 "padding-bottom": (100 / maxNbeltsPerRow) + "%"
364 }
365 },
366 [
367 h("img", {
368 attrs: {
369 src:
370 "/images/pieces/" +
371 // orientation: extra arg useful for some variants:
372 this.vr.getPPpath(m, this.orientation) +
373 V.IMAGE_EXTENSION
374 },
375 "class": { "choice-piece": true },
376 on: onClick
377 })
378 ]
379 );
380 })
381 ) ]
382 );
383 elementArray.unshift(choices);
384 }
385 if (
386 !this.mobileBrowser &&
387 (this.arrows.length > 0 || this.movingArrow.x >= 0)
388 ) {
389 let svgArrows = [];
390 const arrowWidth = squareWidth / 4;
391 this.arrows.forEach(a => {
392 const endPoint = this.adjustEndArrow(a.start, a.end, squareWidth);
393 svgArrows.push(
394 h(
395 "path",
396 {
397 "class": { "svg-arrow": true },
398 attrs: {
399 d: (
400 "M" + a.start.x + "," + a.start.y + " " +
401 "L" + endPoint.x + "," + endPoint.y
402 ),
403 style: "stroke-width:" + arrowWidth + "px"
404 }
405 }
406 )
407 );
408 });
409 if (this.movingArrow.x >= 0) {
410 const endPoint =
411 this.adjustEndArrow(this.startArrow, this.movingArrow, squareWidth);
412 svgArrows.push(
413 h(
414 "path",
415 {
416 "class": { "svg-arrow": true },
417 attrs: {
418 d: (
419 "M" + this.startArrow.x + "," + this.startArrow.y + " " +
420 "L" + endPoint.x + "," + endPoint.y
421 ),
422 style: "stroke-width:" + arrowWidth + "px"
423 }
424 }
425 )
426 );
427 }
428 // Add SVG element for drawing arrows
429 elementArray.push(
430 h(
431 "svg",
432 {
433 attrs: {
434 id: "arrowCanvas",
435 stroke: "none"
436 }
437 },
438 [
439 h(
440 "defs",
441 {},
442 [
443 h(
444 "marker",
445 {
446 attrs: {
447 id: "arrow",
448 markerWidth: (2 * arrowWidth) + "px",
449 markerHeight: (3 * arrowWidth) + "px",
450 markerUnits: "userSpaceOnUse",
451 refX: "0",
452 refY: (1.5 * arrowWidth) + "px",
453 orient: "auto"
454 }
455 },
456 [
457 h(
458 "path",
459 {
460 "class": { "arrow-head": true },
461 attrs: {
462 d: (
463 "M0,0 L0," + (3 * arrowWidth) + " L" +
464 (2 * arrowWidth) + "," + (1.5 * arrowWidth) + " z"
465 )
466 }
467 }
468 )
469 ]
470 )
471 ]
472 )
473 ].concat(svgArrows)
474 )
475 );
476 }
477 let onEvents = {};
478 // NOTE: click = mousedown + mouseup
479 if (this.mobileBrowser) {
480 onEvents = {
481 on: {
482 touchstart: this.mousedown,
483 touchmove: this.mousemove,
484 touchend: this.mouseup
485 }
486 };
487 } else {
488 onEvents = {
489 on: {
490 mousedown: this.mousedown,
491 mousemove: this.mousemove,
492 mouseup: this.mouseup,
493 contextmenu: this.blockContextMenu
494 }
495 };
496 }
497 return h("div", onEvents, elementArray);
498 },
499 methods: {
500 blockContextMenu: function(e) {
501 e.preventDefault();
502 e.stopPropagation();
503 return false;
504 },
505 cancelResetArrows: function() {
506 this.startArrow = null;
507 this.arrows = [];
508 this.circles = {};
509 },
510 adjustEndArrow: function(start, end, squareWidth) {
511 // Simple heuristic for now, just remove 1/3 square.
512 // TODO: should depend on the orientation.
513 const delta = [end.x - start.x, end.y - start.y];
514 const dist = Math.sqrt(delta[0] * delta[0] + delta[1] * delta[1]);
515 const fracSqWidth = squareWidth / 3;
516 return {
517 x: end.x - delta[0] * fracSqWidth / dist,
518 y: end.y - delta[1] * fracSqWidth / dist
519 };
520 },
521 mousedown: function(e) {
522 if (!([1, 3].includes(e.which))) return;
523 e.preventDefault();
524 if (e.which != 3)
525 // Cancel current drawing and circles, if any
526 this.cancelResetArrows();
527 if (e.which == 1 || this.mobileBrowser) {
528 // Mouse left button
529 if (!this.start) {
530 // NOTE: classList[0] is enough: 'piece' is the first assigned class
531 const withPiece = (e.target.classList[0] == "piece");
532 // Emit the click event which could be used by some variants
533 this.$emit(
534 "click-square",
535 getSquareFromId(withPiece ? e.target.parentNode.id : e.target.id)
536 );
537 // Start square must contain a piece.
538 if (!withPiece) return;
539 let parent = e.target.parentNode; //surrounding square
540 // Show possible moves if current player allowed to play
541 const startSquare = getSquareFromId(parent.id);
542 this.possibleMoves = [];
543 const color = this.analyze ? this.vr.turn : this.userColor;
544 if (this.vr.canIplay(color, startSquare))
545 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
546 // For potential drag'n drop, remember start coordinates
547 // (to center the piece on mouse cursor)
548 const rect = parent.getBoundingClientRect();
549 this.start = {
550 x: rect.x + rect.width / 2,
551 y: rect.y + rect.width / 2,
552 id: parent.id
553 };
554 // Add the moving piece to the board, just after current image
555 this.selectedPiece = e.target.cloneNode();
556 Object.assign(
557 this.selectedPiece.style,
558 {
559 position: "absolute",
560 top: 0,
561 display: "inline-block",
562 zIndex: 3000
563 }
564 );
565 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
566 } else {
567 this.processMoveAttempt(e);
568 }
569 } else {
570 // e.which == 3 : mouse right button
571 let elem = e.target;
572 // Next loop because of potential marks
573 while (elem.tagName == "IMG") elem = elem.parentNode;
574 // To center the arrow in square:
575 const rect = elem.getBoundingClientRect();
576 this.startArrow = {
577 x: rect.x + rect.width / 2,
578 y: rect.y + rect.width / 2,
579 id: elem.id
580 };
581 }
582 },
583 mousemove: function(e) {
584 if (!this.selectedPiece && !this.startArrow) return;
585 e.preventDefault();
586 if (!!this.selectedPiece) {
587 // There is an active element: move it around
588 const [offsetX, offsetY] =
589 this.mobileBrowser
590 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
591 : [e.clientX, e.clientY];
592 Object.assign(
593 this.selectedPiece.style,
594 {
595 left: offsetX - this.start.x + "px",
596 top: offsetY - this.start.y + "px"
597 }
598 );
599 }
600 else {
601 let elem = e.target;
602 // Next loop because of potential marks
603 while (elem.tagName == "IMG") elem = elem.parentNode;
604 // To center the arrow in square:
605 if (elem.id != this.startArrow.id) {
606 const rect = elem.getBoundingClientRect();
607 this.movingArrow = {
608 x: rect.x + rect.width / 2,
609 y: rect.y + rect.width / 2
610 };
611 }
612 }
613 },
614 mouseup: function(e) {
615 if (!([1, 3].includes(e.which))) return;
616 e.preventDefault();
617 if (e.which == 1) {
618 if (!this.selectedPiece) return;
619 // Drag'n drop. Selected piece is no longer needed:
620 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
621 delete this.selectedPiece;
622 this.selectedPiece = null;
623 this.processMoveAttempt(e);
624 } else {
625 // Mouse right button (e.which == 3)
626 this.movingArrow = { x: -1, y: -1 };
627 this.processArrowAttempt(e);
628 }
629 },
630 processMoveAttempt: function(e) {
631 // Obtain the move from start and end squares
632 const [offsetX, offsetY] =
633 this.mobileBrowser
634 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
635 : [e.clientX, e.clientY];
636 let landing = document.elementFromPoint(offsetX, offsetY);
637 // Next condition: classList.contains(piece) fails because of marks
638 while (landing.tagName == "IMG") landing = landing.parentNode;
639 if (this.start.id == landing.id) {
640 if (this.click == landing.id) {
641 // Second click on same square: cancel current move
642 this.possibleMoves = [];
643 this.start = null;
644 this.click = "";
645 } else this.click = landing.id;
646 return;
647 }
648 this.start = null;
649 // OK: process move attempt, landing is a square node
650 let endSquare = getSquareFromId(landing.id);
651 let moves = this.findMatchingMoves(endSquare);
652 this.possibleMoves = [];
653 if (moves.length > 1) {
654 this.clickTime = Date.now();
655 this.choices = moves;
656 } else if (moves.length == 1) this.play(moves[0]);
657 // else: forbidden move attempt
658 },
659 processArrowAttempt: function(e) {
660 // Obtain the arrow from start and end squares
661 const [offsetX, offsetY] = [e.clientX, e.clientY];
662 let landing = document.elementFromPoint(offsetX, offsetY);
663 // Next condition: classList.contains(piece) fails because of marks
664 while (landing.tagName == "IMG") landing = landing.parentNode;
665 if (this.startArrow.id == landing.id)
666 // Draw (or erase) a circle
667 this.$set(this.circles, landing.id, !this.circles[landing.id]);
668 else {
669 // OK: add arrow, landing is a new square
670 const rect = landing.getBoundingClientRect();
671 this.arrows.push({
672 start: {
673 x: this.startArrow.x,
674 y: this.startArrow.y
675 },
676 end: {
677 x: rect.x + rect.width / 2,
678 y: rect.y + rect.width / 2
679 }
680 });
681 }
682 this.startArrow = null;
683 },
684 findMatchingMoves: function(endSquare) {
685 // Run through moves list and return the matching set (if promotions...)
686 return (
687 this.possibleMoves.filter(m => {
688 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
689 })
690 );
691 },
692 play: function(move) {
693 this.$emit("play-move", move);
694 }
695 }
696 };
697 </script>
698
699 <style lang="sass" scoped>
700 // NOTE: no variants with reserve of size != 8
701 .game.reserve-div
702 margin-bottom: 18px
703 .reserve-count
704 padding-left: 40%
705 .reserve-row
706 margin-bottom: 15px
707
708 .full-width
709 width: 100%
710
711 .game
712 user-select: none
713 width: 100%
714 margin: 0
715 .board
716 cursor: pointer
717
718 #choices
719 user-select: none
720 margin: 0
721 position: absolute
722 z-index: 300
723 overflow-y: inherit
724 background-color: rgba(0,0,0,0)
725 img
726 cursor: pointer
727 background-color: #e6ee9c
728 &:hover
729 background-color: skyblue
730 &.choice-piece
731 width: 100%
732 height: auto
733 display: block
734
735 img.ghost
736 position: absolute
737 opacity: 0.5
738 top: 0
739
740 #arrowCanvas
741 pointer-events: none
742 position: absolute
743 top: 0
744 left: 0
745 width: 100%
746 height: 100%
747
748 .svg-arrow
749 opacity: 0.65
750 stroke: #5f0e78
751 fill: none
752 marker-end: url(#arrow)
753
754 .arrow-head
755 fill: #5f0e78
756
757 .incheck-light
758 background-color: rgba(204, 51, 0, 0.7) !important
759 .incheck-dark
760 background-color: rgba(204, 51, 0, 0.9) !important
761
762 .light-square.lichess
763 background-color: #f0d9b5;
764 .dark-square.lichess
765 background-color: #b58863;
766
767 .light-square.chesscom
768 background-color: #e5e5ca;
769 .dark-square.chesscom
770 background-color: #6f8f57;
771
772 .light-square.chesstempo
773 background-color: #dfdfdf;
774 .dark-square.chesstempo
775 background-color: #7287b6;
776
777 // TODO: no predefined highlight colors, but layers. How?
778
779 .light-square.lichess.highlight-light
780 background-color: #cdd26a
781 .dark-square.lichess.highlight-dark
782 background-color: #aaa23a
783
784 .light-square.chesscom.highlight-light
785 background-color: #f7f783
786 .dark-square.chesscom.highlight-dark
787 background-color: #bacb44
788
789 .light-square.chesstempo.highlight-light
790 background-color: #9f9fff
791 .dark-square.chesstempo.highlight-dark
792 background-color: #557fff
793
794 </style>