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