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