First draft of arrows + circles on board. Fix multi-connect detection
[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 if (this.choices.length > 0 && !!boardElt) {
307 // No choices to show at first drawing
308 const squareWidth = boardElt.offsetWidth / sizeY;
309 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
310 const maxNbeltsPerRow = Math.min(this.choices.length, sizeY);
311 let topOffset = offset[0] + (sizeY / 2) * squareWidth - squareWidth / 2;
312 let choicesHeight = squareWidth;
313 if (this.choices.length >= sizeY) {
314 // A second row is required (Eightpieces variant)
315 topOffset -= squareWidth / 2;
316 choicesHeight *= 2;
317 }
318 const choices = h(
319 "div",
320 {
321 attrs: { id: "choices" },
322 "class": { row: true },
323 style: {
324 top: topOffset + "px",
325 left:
326 offset[1] +
327 (squareWidth * Math.max(sizeY - this.choices.length, 0)) / 2 +
328 "px",
329 width: (maxNbeltsPerRow * squareWidth) + "px",
330 height: choicesHeight + "px"
331 }
332 },
333 [ h(
334 "div",
335 {
336 "class": { "full-width": true }
337 },
338 this.choices.map(m => {
339 // A "choice" is a move
340 const applyMove = (e) => {
341 e.stopPropagation();
342 // Force a delay between move is shown and clicked
343 // (otherwise a "double-click" bug might occur)
344 if (Date.now() - this.clickTime < 200) return;
345 this.choices = [];
346 this.play(m);
347 };
348 const onClick =
349 this.mobileBrowser
350 ? { touchend: applyMove }
351 : { mouseup: applyMove };
352 return h(
353 "div",
354 {
355 "class": {
356 board: true,
357 ["board" + sizeY]: true
358 },
359 style: {
360 width: (100 / maxNbeltsPerRow) + "%",
361 "padding-bottom": (100 / maxNbeltsPerRow) + "%"
362 }
363 },
364 [
365 h("img", {
366 attrs: {
367 src:
368 "/images/pieces/" +
369 // orientation: extra arg useful for some variants:
370 this.vr.getPPpath(m, this.orientation) +
371 V.IMAGE_EXTENSION
372 },
373 "class": { "choice-piece": true },
374 on: onClick
375 })
376 ]
377 );
378 })
379 ) ]
380 );
381 elementArray.unshift(choices);
382 }
383 if (
384 !this.mobileBrowser &&
385 (this.arrows.length > 0 || this.movingArrow.x >= 0)
386 ) {
387 let svgArrows = [];
388 this.arrows.forEach(a => {
389 svgArrows.push(
390 h(
391 "path",
392 {
393 "class": { "svg-arrow": true },
394 attrs: {
395 d: (
396 "M" + a.start.x + "," + a.start.y + " " +
397 "L" + a.end.x + "," + a.end.y
398 )
399 }
400 }
401 )
402 );
403 });
404 if (this.movingArrow.x >= 0) {
405 svgArrows.push(
406 h(
407 "path",
408 {
409 "class": { "svg-arrow": true },
410 attrs: {
411 d: (
412 "M" + this.startArrow.x + "," + this.startArrow.y + " " +
413 "L" + this.movingArrow.x + "," + this.movingArrow.y
414 )
415 }
416 }
417 )
418 );
419 }
420 // Add SVG element for drawing arrows
421 elementArray.push(
422 h(
423 "svg",
424 {
425 attrs: {
426 id: "arrowCanvas",
427 stroke: "none"
428 }
429 },
430 [
431 h(
432 "defs",
433 {},
434 [
435 h(
436 "marker",
437 {
438 attrs: {
439 id: "arrow",
440 markerWidth: "2",
441 markerHeight: "2",
442 markerUnits: "strokeWidth",
443 refX: "0",
444 refY: "1",
445 orient: "auto"
446 }
447 },
448 [
449 h(
450 "path",
451 {
452 attrs: {
453 d: "M0,0 L0,2 L2,1 z",
454 style: "fill: blue"
455 }
456 }
457 )
458 ]
459 )
460 ]
461 )
462 ].concat(svgArrows)
463 )
464 );
465 }
466 let onEvents = {};
467 // NOTE: click = mousedown + mouseup
468 if (this.mobileBrowser) {
469 onEvents = {
470 on: {
471 touchstart: this.mousedown,
472 touchmove: this.mousemove,
473 touchend: this.mouseup
474 }
475 };
476 } else {
477 onEvents = {
478 on: {
479 mousedown: this.mousedown,
480 mousemove: this.mousemove,
481 mouseup: this.mouseup,
482 contextmenu: this.blockContextMenu
483 }
484 };
485 }
486 return h("div", onEvents, elementArray);
487 },
488 methods: {
489 blockContextMenu: function(e) {
490 e.preventDefault();
491 e.stopPropagation();
492 return false;
493 },
494 cancelResetArrows: function() {
495 this.startArrow = null;
496 this.arrows = [];
497 this.circles = {};
498 },
499 mousedown: function(e) {
500 if (!([1, 3].includes(e.which))) return;
501 e.preventDefault();
502 if (e.which != 3)
503 // Cancel current drawing and circles, if any
504 this.cancelResetArrows();
505 if (e.which == 1 || this.mobileBrowser) {
506 // Mouse left button
507 if (!this.start) {
508 // NOTE: classList[0] is enough: 'piece' is the first assigned class
509 const withPiece = (e.target.classList[0] == "piece");
510 // Emit the click event which could be used by some variants
511 this.$emit(
512 "click-square",
513 getSquareFromId(withPiece ? e.target.parentNode.id : e.target.id)
514 );
515 // Start square must contain a piece.
516 if (!withPiece) return;
517 let parent = e.target.parentNode; //surrounding square
518 // Show possible moves if current player allowed to play
519 const startSquare = getSquareFromId(parent.id);
520 this.possibleMoves = [];
521 const color = this.analyze ? this.vr.turn : this.userColor;
522 if (this.vr.canIplay(color, startSquare))
523 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
524 // For potential drag'n drop, remember start coordinates
525 // (to center the piece on mouse cursor)
526 const rect = parent.getBoundingClientRect();
527 this.start = {
528 x: rect.x + rect.width / 2,
529 y: rect.y + rect.width / 2,
530 id: parent.id
531 };
532 // Add the moving piece to the board, just after current image
533 this.selectedPiece = e.target.cloneNode();
534 Object.assign(
535 this.selectedPiece.style,
536 {
537 position: "absolute",
538 top: 0,
539 display: "inline-block",
540 zIndex: 3000
541 }
542 );
543 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
544 } else {
545 this.processMoveAttempt(e);
546 }
547 } else {
548 // e.which == 3 : mouse right button
549 let elem = e.target;
550 // Next loop because of potential marks
551 while (elem.tagName == "IMG") elem = elem.parentNode;
552 // To center the arrow in square:
553 const rect = elem.getBoundingClientRect();
554 this.startArrow = {
555 x: rect.x + rect.width / 2,
556 y: rect.y + rect.width / 2,
557 id: elem.id
558 };
559 }
560 },
561 mousemove: function(e) {
562 if (!this.selectedPiece && !this.startArrow) return;
563 e.preventDefault();
564 if (!!this.selectedPiece) {
565 // There is an active element: move it around
566 const [offsetX, offsetY] =
567 this.mobileBrowser
568 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
569 : [e.clientX, e.clientY];
570 Object.assign(
571 this.selectedPiece.style,
572 {
573 left: offsetX - this.start.x + "px",
574 top: offsetY - this.start.y + "px"
575 }
576 );
577 }
578 else {
579 let elem = e.target;
580 // Next loop because of potential marks
581 while (elem.tagName == "IMG") elem = elem.parentNode;
582 // To center the arrow in square:
583 if (elem.id != this.startArrow.id) {
584 const rect = elem.getBoundingClientRect();
585 this.movingArrow = {
586 x: rect.x + rect.width / 2,
587 y: rect.y + rect.width / 2
588 };
589 }
590 }
591 },
592 mouseup: function(e) {
593 if (!([1, 3].includes(e.which))) return;
594 e.preventDefault();
595 if (e.which == 1) {
596 if (!this.selectedPiece) return;
597 // Drag'n drop. Selected piece is no longer needed:
598 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
599 delete this.selectedPiece;
600 this.selectedPiece = null;
601 this.processMoveAttempt(e);
602 } else {
603 // Mouse right button (e.which == 3)
604 this.movingArrow = { x: -1, y: -1 };
605 this.processArrowAttempt(e);
606 }
607 },
608 processMoveAttempt: function(e) {
609 // Obtain the move from start and end squares
610 const [offsetX, offsetY] =
611 this.mobileBrowser
612 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
613 : [e.clientX, e.clientY];
614 let landing = document.elementFromPoint(offsetX, offsetY);
615 // Next condition: classList.contains(piece) fails because of marks
616 while (landing.tagName == "IMG") landing = landing.parentNode;
617 if (this.start.id == landing.id) {
618 if (this.click == landing.id) {
619 // Second click on same square: cancel current move
620 this.possibleMoves = [];
621 this.start = null;
622 this.click = "";
623 } else this.click = landing.id;
624 return;
625 }
626 this.start = null;
627 // OK: process move attempt, landing is a square node
628 let endSquare = getSquareFromId(landing.id);
629 let moves = this.findMatchingMoves(endSquare);
630 this.possibleMoves = [];
631 if (moves.length > 1) {
632 this.clickTime = Date.now();
633 this.choices = moves;
634 } else if (moves.length == 1) this.play(moves[0]);
635 // else: forbidden move attempt
636 },
637 processArrowAttempt: function(e) {
638 // Obtain the arrow from start and end squares
639 const [offsetX, offsetY] = [e.clientX, e.clientY];
640 let landing = document.elementFromPoint(offsetX, offsetY);
641 // Next condition: classList.contains(piece) fails because of marks
642 while (landing.tagName == "IMG") landing = landing.parentNode;
643 if (this.startArrow.id == landing.id)
644 // Draw (or erase) a circle
645 this.$set(this.circles, landing.id, !this.circles[landing.id]);
646 else {
647 // OK: add arrow, landing is a new square
648 const rect = landing.getBoundingClientRect();
649 this.arrows.push({
650 start: {
651 x: this.startArrow.x,
652 y: this.startArrow.y
653 },
654 end: {
655 x: rect.x + rect.width / 2,
656 y: rect.y + rect.width / 2
657 }
658 });
659 }
660 this.startArrow = null;
661 },
662 findMatchingMoves: function(endSquare) {
663 // Run through moves list and return the matching set (if promotions...)
664 return (
665 this.possibleMoves.filter(m => {
666 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
667 })
668 );
669 },
670 play: function(move) {
671 this.$emit("play-move", move);
672 }
673 }
674 };
675 </script>
676
677 <style lang="sass" scoped>
678 // NOTE: no variants with reserve of size != 8
679 .game.reserve-div
680 margin-bottom: 18px
681 .reserve-count
682 padding-left: 40%
683 .reserve-row
684 margin-bottom: 15px
685
686 .full-width
687 width: 100%
688
689 .game
690 user-select: none
691 width: 100%
692 margin: 0
693 .board
694 cursor: pointer
695
696 #choices
697 user-select: none
698 margin: 0
699 position: absolute
700 z-index: 300
701 overflow-y: inherit
702 background-color: rgba(0,0,0,0)
703 img
704 cursor: pointer
705 background-color: #e6ee9c
706 &:hover
707 background-color: skyblue
708 &.choice-piece
709 width: 100%
710 height: auto
711 display: block
712
713 img.ghost
714 position: absolute
715 opacity: 0.5
716 top: 0
717
718 #arrowCanvas
719 pointer-events: none
720 position: absolute
721 top: 0
722 left: 0
723 width: 100%
724 height: 100%
725
726 .svg-arrow
727 opacity: 0.65
728 stroke: #5f0e78
729 stroke-width: 10px
730 fill: none
731 marker-end: url(#arrow)
732
733 .incheck-light
734 background-color: rgba(204, 51, 0, 0.7) !important
735 .incheck-dark
736 background-color: rgba(204, 51, 0, 0.9) !important
737
738 .light-square.lichess
739 background-color: #f0d9b5;
740 .dark-square.lichess
741 background-color: #b58863;
742
743 .light-square.chesscom
744 background-color: #e5e5ca;
745 .dark-square.chesscom
746 background-color: #6f8f57;
747
748 .light-square.chesstempo
749 background-color: #dfdfdf;
750 .dark-square.chesstempo
751 background-color: #7287b6;
752
753 // TODO: no predefined highlight colors, but layers. How?
754
755 .light-square.lichess.highlight-light
756 background-color: #cdd26a
757 .dark-square.lichess.highlight-dark
758 background-color: #aaa23a
759
760 .light-square.chesscom.highlight-light
761 background-color: #f7f783
762 .dark-square.chesscom.highlight-dark
763 background-color: #bacb44
764
765 .light-square.chesstempo.highlight-light
766 background-color: #9f9fff
767 .dark-square.chesstempo.highlight-dark
768 background-color: #557fff
769
770 </style>