Adjustments + add en-passant to Zen rules
[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 },
193 attrs: {
194 id: getSquareId({ x: ci, y: cj })
195 }
196 },
197 elems
198 );
199 })
200 );
201 })
202 );
203 if (!!this.vr.reserve) {
204 const playingColor = this.userColor || "w"; //default for an observer
205 const shiftIdx = playingColor == "w" ? 0 : 1;
206 // Some variants have more than sizeY reserve pieces (Clorange: 10)
207 const reserveSquareNb = Math.max(sizeY, V.RESERVE_PIECES.length);
208 let myReservePiecesArray = [];
209 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
210 const qty = this.vr.reserve[playingColor][V.RESERVE_PIECES[i]];
211 myReservePiecesArray.push(
212 h(
213 "div",
214 {
215 "class": { board: true, ["board" + reserveSquareNb]: true },
216 attrs: { id: getSquareId({ x: sizeX + shiftIdx, y: i }) },
217 style: { opacity: qty > 0 ? 1 : 0.35 }
218 },
219 [
220 h("img", {
221 // NOTE: class "reserve" not used currently
222 "class": { piece: true, reserve: true },
223 attrs: {
224 src:
225 "/images/pieces/" +
226 this.vr.getReservePpath(i, playingColor, orientation) +
227 ".svg"
228 }
229 }),
230 h(
231 "sup",
232 {
233 "class": { "reserve-count": true },
234 style: { top: "calc(100% + 5px)" }
235 },
236 [ qty ]
237 )
238 ]
239 )
240 );
241 }
242 let oppReservePiecesArray = [];
243 const oppCol = V.GetOppCol(playingColor);
244 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
245 const qty = this.vr.reserve[oppCol][V.RESERVE_PIECES[i]];
246 oppReservePiecesArray.push(
247 h(
248 "div",
249 {
250 "class": { board: true, ["board" + reserveSquareNb]: true },
251 attrs: { id: getSquareId({ x: sizeX + (1 - shiftIdx), y: i }) },
252 style: { opacity: qty > 0 ? 1 : 0.35 }
253 },
254 [
255 h("img", {
256 "class": { piece: true, reserve: true },
257 attrs: {
258 src:
259 "/images/pieces/" +
260 this.vr.getReservePpath(i, oppCol, orientation) +
261 ".svg"
262 }
263 }),
264 h(
265 "sup",
266 {
267 "class": { "reserve-count": true },
268 style: { top: "calc(100% + 5px)" }
269 },
270 [ qty ]
271 )
272 ]
273 )
274 );
275 }
276 const myReserveTop = (
277 (playingColor == 'w' && orientation == 'b') ||
278 (playingColor == 'b' && orientation == 'w')
279 );
280 // Center reserves, assuming same number of pieces for each side:
281 const nbReservePieces = myReservePiecesArray.length;
282 const marginLeft =
283 ((100 - nbReservePieces * (100 / reserveSquareNb)) / 2) + "%";
284 const reserveTop =
285 h(
286 "div",
287 {
288 "class": {
289 game: true,
290 "reserve-div": true
291 },
292 style: {
293 "margin-left": marginLeft
294 }
295 },
296 [
297 h(
298 "div",
299 {
300 "class": {
301 row: true,
302 "reserve-row": true
303 }
304 },
305 myReserveTop ? myReservePiecesArray : oppReservePiecesArray
306 )
307 ]
308 );
309 var reserveBottom =
310 h(
311 "div",
312 {
313 "class": {
314 game: true,
315 "reserve-div": true
316 },
317 style: {
318 "margin-left": marginLeft
319 }
320 },
321 [
322 h(
323 "div",
324 {
325 "class": {
326 row: true,
327 "reserve-row": true
328 }
329 },
330 myReserveTop ? oppReservePiecesArray : myReservePiecesArray
331 )
332 ]
333 );
334 elementArray.push(reserveTop);
335 }
336 elementArray.push(gameDiv);
337 if (!!this.vr.reserve) elementArray.push(reserveBottom);
338 const boardElt = document.getElementById("gamePosition");
339 // boardElt might be undefine (at first drawing)
340 if (this.choices.length > 0 && !!boardElt) {
341 const squareWidth = boardElt.offsetWidth / sizeY;
342 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
343 const maxNbeltsPerRow = Math.min(this.choices.length, sizeY);
344 let topOffset = offset[0] + (sizeY / 2) * squareWidth - squareWidth / 2;
345 let choicesHeight = squareWidth;
346 if (this.choices.length >= sizeY) {
347 // A second row is required (Eightpieces variant)
348 topOffset -= squareWidth / 2;
349 choicesHeight *= 2;
350 }
351 const choices = h(
352 "div",
353 {
354 attrs: { id: "choices" },
355 "class": { row: true },
356 style: {
357 top: topOffset + "px",
358 left:
359 offset[1] +
360 (squareWidth * Math.max(sizeY - this.choices.length, 0)) / 2 +
361 "px",
362 width: (maxNbeltsPerRow * squareWidth) + "px",
363 height: choicesHeight + "px"
364 }
365 },
366 [ h(
367 "div",
368 {
369 "class": { "full-width": true }
370 },
371 this.choices.map(m => {
372 // A "choice" is a move
373 const applyMove = (e) => {
374 e.stopPropagation();
375 // Force a delay between move is shown and clicked
376 // (otherwise a "double-click" bug might occur)
377 if (Date.now() - this.clickTime < 200) return;
378 this.choices = [];
379 this.play(m);
380 };
381 const onClick =
382 this.mobileBrowser
383 ? { touchend: applyMove }
384 : { mouseup: applyMove };
385 return h(
386 "div",
387 {
388 "class": {
389 board: true,
390 ["board" + sizeY]: true
391 },
392 style: {
393 width: (100 / maxNbeltsPerRow) + "%",
394 "padding-bottom": (100 / maxNbeltsPerRow) + "%"
395 }
396 },
397 [
398 h("img", {
399 attrs: {
400 src:
401 "/images/pieces/" +
402 // orientation: extra arg useful for some variants:
403 this.vr.getPPpath(m, this.orientation) +
404 V.IMAGE_EXTENSION
405 },
406 "class": { "choice-piece": true },
407 on: onClick
408 })
409 ]
410 );
411 })
412 ) ]
413 );
414 elementArray.unshift(choices);
415 }
416 let onEvents = {};
417 // NOTE: click = mousedown + mouseup
418 if (this.mobileBrowser) {
419 onEvents = {
420 on: {
421 touchstart: this.mousedown,
422 touchmove: this.mousemove,
423 touchend: this.mouseup
424 }
425 };
426 } else {
427 onEvents = {
428 on: {
429 mousedown: this.mousedown,
430 mousemove: this.mousemove,
431 mouseup: this.mouseup,
432 contextmenu: this.blockContextMenu
433 }
434 };
435 }
436 return (
437 h(
438 "div",
439 Object.assign({ attrs: { id: "rootBoardElement" } }, onEvents),
440 elementArray
441 )
442 );
443 },
444 updated: function() {
445 this.re_setDrawings();
446 },
447 methods: {
448 blockContextMenu: function(e) {
449 e.preventDefault();
450 e.stopPropagation();
451 return false;
452 },
453 cancelResetArrows: function() {
454 this.startArrow = null;
455 this.arrows = [];
456 this.circles = {};
457 const curCanvas = document.getElementById("arrowCanvas");
458 if (!!curCanvas) curCanvas.parentNode.removeChild(curCanvas);
459 },
460 coordsToXY: function(coords, top, left, squareWidth) {
461 return {
462 // [1] for x and [0] for y because conventions in rules are inversed.
463 x: (
464 left + window.scrollX +
465 (
466 squareWidth *
467 (this.orientation == 'w' ? coords[1] : (V.size.y - coords[1]))
468 )
469 ),
470 y: (
471 top + window.scrollY +
472 (
473 squareWidth *
474 (this.orientation == 'w' ? coords[0] : (V.size.x - coords[0]))
475 )
476 )
477 };
478 },
479 computeEndArrow: function(start, end, top, left, squareWidth) {
480 const endCoords = this.coordsToXY(end, top, left, squareWidth);
481 const delta = [endCoords.x - start.x, endCoords.y - start.y];
482 const dist = Math.sqrt(delta[0] * delta[0] + delta[1] * delta[1]);
483 // Simple heuristic for now, just remove 1/3 square.
484 // TODO: should depend on the orientation.
485 const fracSqWidth = squareWidth / 3;
486 return {
487 x: endCoords.x - delta[0] * fracSqWidth / dist,
488 y: endCoords.y - delta[1] * fracSqWidth / dist
489 };
490 },
491 drawCurrentArrow: function() {
492 const boardElt = document.getElementById("gamePosition");
493 const squareWidth = boardElt.offsetWidth / V.size.y;
494 const bPos = boardElt.getBoundingClientRect();
495 const aStart =
496 this.coordsToXY(
497 [this.startArrow[0] + 0.5, this.startArrow[1] + 0.5],
498 bPos.top, bPos.left, squareWidth);
499 const aEnd =
500 this.computeEndArrow(
501 aStart, [this.movingArrow[0] + 0.5, this.movingArrow[1] + 0.5],
502 bPos.top, bPos.left, squareWidth);
503 let currentArrow = document.getElementById("currentArrow");
504 const d =
505 "M" + aStart.x + "," + aStart.y + " " + "L" + aEnd.x + "," + aEnd.y;
506 const arrowWidth = squareWidth / 4;
507 if (!!currentArrow) currentArrow.setAttribute("d", d);
508 else {
509 let domArrow =
510 document.createElementNS("http://www.w3.org/2000/svg", "path");
511 domArrow.classList.add("svg-arrow");
512 domArrow.id = "currentArrow";
513 domArrow.setAttribute("d", d);
514 domArrow.style = "stroke-width:" + arrowWidth + "px";
515 document.getElementById("arrowCanvas")
516 .insertAdjacentElement("beforeend", domArrow);
517 }
518 },
519 addArrow: function(arrow) {
520 this.arrows.push(arrow);
521 // Also add to DOM:
522 const boardElt = document.getElementById("gamePosition");
523 const squareWidth = boardElt.offsetWidth / V.size.y;
524 const bPos = boardElt.getBoundingClientRect();
525 const newArrow =
526 this.getSvgArrow(arrow, bPos.top, bPos.left, squareWidth);
527 document.getElementById("arrowCanvas")
528 .insertAdjacentElement("beforeend", newArrow);
529 },
530 getSvgArrow: function(arrow, top, left, squareWidth) {
531 const aStart =
532 this.coordsToXY(
533 [arrow.start[0] + 0.5, arrow.start[1] + 0.5],
534 top, left, squareWidth);
535 const aEnd =
536 this.computeEndArrow(
537 aStart, [arrow.end[0] + 0.5, arrow.end[1] + 0.5],
538 top, left, squareWidth);
539 const arrowWidth = squareWidth / 4;
540 let path =
541 document.createElementNS("http://www.w3.org/2000/svg", "path");
542 path.classList.add("svg-arrow");
543 path.setAttribute(
544 "d",
545 "M" + aStart.x + "," + aStart.y + " " + "L" + aEnd.x + "," + aEnd.y
546 );
547 path.style = "stroke-width:" + arrowWidth + "px";
548 return path;
549 },
550 re_setDrawings: function() {
551 // Remove current canvas, if any
552 const curCanvas = document.getElementById("arrowCanvas");
553 if (!!curCanvas) curCanvas.parentNode.removeChild(curCanvas);
554 // Add some drawing on board (for some variants + arrows and circles)
555 const boardElt = document.getElementById("gamePosition");
556 const squareWidth = boardElt.offsetWidth / V.size.y;
557 const bPos = boardElt.getBoundingClientRect();
558 let svgArrows = [];
559 this.arrows.forEach(a => {
560 svgArrows.push(this.getSvgArrow(a, bPos.top, bPos.left, squareWidth));
561 });
562 let vLines = [];
563 if (!!V.Lines) {
564 V.Lines.forEach(line => {
565 const lStart =
566 this.coordsToXY(line[0], bPos.top, bPos.left, squareWidth);
567 const lEnd =
568 this.coordsToXY(line[1], bPos.top, bPos.left, squareWidth);
569 let path =
570 document.createElementNS("http://www.w3.org/2000/svg", "path");
571 path.classList.add("svg-line");
572 path.setAttribute(
573 "d",
574 "M" + lStart.x + "," + lStart.y + " " +
575 "L" + lEnd.x + "," + lEnd.y
576 );
577 vLines.push(path);
578 });
579 }
580 let arrowCanvas =
581 document.createElementNS("http://www.w3.org/2000/svg", "svg");
582 arrowCanvas.id = "arrowCanvas";
583 arrowCanvas.setAttribute("stroke", "none");
584 let defs =
585 document.createElementNS("http://www.w3.org/2000/svg", "defs");
586 const arrowWidth = squareWidth / 4;
587 let marker =
588 document.createElementNS("http://www.w3.org/2000/svg", "marker");
589 marker.id = "arrow";
590 marker.setAttribute("markerWidth", (2 * arrowWidth) + "px");
591 marker.setAttribute("markerHeight", (3 * arrowWidth) + "px");
592 marker.setAttribute("markerUnits", "userSpaceOnUse");
593 marker.setAttribute("refX", "0");
594 marker.setAttribute("refY", (1.5 * arrowWidth) + "px");
595 marker.setAttribute("orient", "auto");
596 let head =
597 document.createElementNS("http://www.w3.org/2000/svg", "path");
598 head.classList.add("arrow-head");
599 head.setAttribute(
600 "d",
601 "M0,0 L0," + (3 * arrowWidth) + " L" +
602 (2 * arrowWidth) + "," + (1.5 * arrowWidth) + " z"
603 );
604 marker.appendChild(head);
605 defs.appendChild(marker);
606 arrowCanvas.appendChild(defs);
607 svgArrows.concat(vLines).forEach(av => arrowCanvas.appendChild(av));
608 document.getElementById("rootBoardElement").appendChild(arrowCanvas);
609 },
610 mousedown: function(e) {
611 e.preventDefault();
612 if (!this.mobileBrowser && e.which != 3)
613 // Cancel current drawing and circles, if any
614 this.cancelResetArrows();
615 if (this.mobileBrowser || e.which == 1) {
616 // Mouse left button
617 if (!this.start) {
618 this.containerPos =
619 document.getElementById("boardContainer").getBoundingClientRect();
620 // NOTE: classList[0] is enough: 'piece' is the first assigned class
621 const withPiece = (e.target.classList[0] == "piece");
622 // Emit the click event which could be used by some variants
623 this.$emit(
624 "click-square",
625 getSquareFromId(withPiece ? e.target.parentNode.id : e.target.id)
626 );
627 // Start square must contain a piece.
628 if (!withPiece) return;
629 let parent = e.target.parentNode; //surrounding square
630 // Show possible moves if current player allowed to play
631 const startSquare = getSquareFromId(parent.id);
632 this.possibleMoves = [];
633 const color = this.analyze ? this.vr.turn : this.userColor;
634 if (this.vr.canIplay(color, startSquare))
635 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
636 // For potential drag'n drop, remember start coordinates
637 // (to center the piece on mouse cursor)
638 const rect = parent.getBoundingClientRect();
639 this.start = {
640 x: rect.x + rect.width / 2,
641 y: rect.y + rect.width / 2,
642 id: parent.id
643 };
644 // Add the moving piece to the board, just after current image
645 this.selectedPiece = e.target.cloneNode();
646 Object.assign(
647 this.selectedPiece.style,
648 {
649 position: "absolute",
650 top: 0,
651 display: "inline-block",
652 zIndex: 3000
653 }
654 );
655 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
656 } else {
657 this.processMoveAttempt(e);
658 }
659 } else if (e.which == 3) {
660 // Mouse right button
661 this.containerPos =
662 document.getElementById("gamePosition").getBoundingClientRect();
663 let elem = e.target;
664 // Next loop because of potential marks
665 while (elem.tagName == "IMG") elem = elem.parentNode;
666 this.startArrow = getSquareFromId(elem.id);
667 }
668 },
669 mousemove: function(e) {
670 if (!this.selectedPiece && !this.startArrow) return;
671 // Cancel if off boardContainer
672 const [offsetX, offsetY] =
673 this.mobileBrowser
674 ?
675 [
676 e.changedTouches[0].pageX,
677 // TODO: fixing attempt for smartphones, removing window.scrollY
678 e.changedTouches[0].pageY - window.scrollY
679 ]
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 ?
760 [
761 e.changedTouches[0].pageX,
762 e.changedTouches[0].pageY - window.scrollY
763 ]
764 : [e.clientX, e.clientY];
765 let landing = document.elementFromPoint(offsetX, offsetY);
766 // Next condition: classList.contains(piece) fails because of marks
767 while (landing.tagName == "IMG") landing = landing.parentNode;
768 if (this.start.id == landing.id) {
769 if (this.click == landing.id) {
770 // Second click on same square: cancel current move
771 this.possibleMoves = [];
772 this.start = null;
773 this.click = "";
774 } else this.click = landing.id;
775 return;
776 }
777 this.start = null;
778 // OK: process move attempt, landing is a square node
779 let endSquare = getSquareFromId(landing.id);
780 let moves = this.findMatchingMoves(endSquare);
781 this.possibleMoves = [];
782 if (moves.length > 1) {
783 this.clickTime = Date.now();
784 this.choices = moves;
785 } else if (moves.length == 1) this.play(moves[0]);
786 // else: forbidden move attempt
787 },
788 processArrowAttempt: function(e) {
789 // Obtain the arrow from start and end squares
790 const [offsetX, offsetY] = [e.clientX, e.clientY];
791 let landing = document.elementFromPoint(offsetX, offsetY);
792 // Next condition: classList.contains(piece) fails because of marks
793 while (landing.tagName == "IMG") landing = landing.parentNode;
794 const landingCoords = getSquareFromId(landing.id);
795 if (
796 this.startArrow[0] == landingCoords[0] &&
797 this.startArrow[1] == landingCoords[1]
798 ) {
799 // Draw (or erase) a circle
800 this.$set(this.circles, landing.id, !this.circles[landing.id]);
801 }
802 else {
803 // OK: add arrow, landing is a new square
804 const currentArrow = document.getElementById("currentArrow");
805 currentArrow.parentNode.removeChild(currentArrow);
806 this.addArrow({
807 start: this.startArrow,
808 end: landingCoords
809 });
810 }
811 this.startArrow = null;
812 },
813 findMatchingMoves: function(endSquare) {
814 // Run through moves list and return the matching set (if promotions...)
815 return (
816 this.possibleMoves.filter(m => {
817 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
818 })
819 );
820 },
821 play: function(move) {
822 this.$emit("play-move", move);
823 }
824 }
825 };
826 </script>
827
828 <style lang="sass">
829 // SVG dynamically added, so not scoped
830 #arrowCanvas
831 pointer-events: none
832 position: absolute
833 top: 0
834 left: 0
835 width: 100%
836 height: 100%
837
838 .svg-arrow
839 opacity: 0.65
840 stroke: #5f0e78
841 fill: none
842 marker-end: url(#arrow)
843
844 .svg-line
845 stroke: black
846
847 .arrow-head
848 fill: #5f0e78
849 </style>
850
851 <style lang="sass" scoped>
852 @import "@/styles/_board_squares_img.sass";
853
854 //.game.reserve-div
855 // TODO: would be cleaner to restrict width so that it doesn't overflow
856 // Commented out because pieces would disappear over the board otherwise:
857 //overflow: hidden
858 .reserve-count
859 width: 100%
860 text-align: center
861 display: inline-block
862 position: absolute
863 .reserve-row
864 margin-bottom: 15px
865
866 .full-width
867 width: 100%
868
869 .game
870 user-select: none
871 width: 100%
872 margin: 0
873 .board
874 cursor: pointer
875
876 #choices
877 user-select: none
878 margin: 0
879 position: absolute
880 z-index: 300
881 overflow-y: inherit
882 background-color: rgba(0,0,0,0)
883 img
884 cursor: pointer
885 background-color: #e6ee9c
886 &:hover
887 background-color: skyblue
888 &.choice-piece
889 width: 100%
890 height: auto
891 display: block
892
893 img.ghost
894 // NOTE: no need to set z-index here, since opacity is low
895 position: absolute
896 opacity: 0.5
897 top: 0
898
899 .incheck-light
900 background-color: rgba(204, 51, 0, 0.7) !important
901 .incheck-dark
902 background-color: rgba(204, 51, 0, 0.9) !important
903
904 .light-square.lichess
905 background-color: #f0d9b5
906 .dark-square.lichess
907 background-color: #b58863
908
909 .light-square.chesscom
910 background-color: #e5e5ca
911 .dark-square.chesscom
912 background-color: #6f8f57
913
914 .light-square.chesstempo
915 background-color: #dfdfdf
916 .dark-square.chesstempo
917 background-color: #7287b6
918
919 .middle-square.lichess
920 background-color: #D3B18C
921
922 .middle-square.chesscom
923 background-color: #AABA91
924
925 .middle-square.chesstempo
926 background-color: #A9B3CB
927
928 // TODO: no predefined highlight colors, but layers. How?
929
930 .light-square.lichess.highlight-light
931 background-color: #cdd26a
932 .dark-square.lichess.highlight-dark
933 background-color: #aaa23a
934
935 .light-square.chesscom.highlight-light
936 background-color: #f7f783
937 .dark-square.chesscom.highlight-dark
938 background-color: #bacb44
939
940 .light-square.chesstempo.highlight-light
941 background-color: #9f9fff
942 .dark-square.chesstempo.highlight-dark
943 background-color: #557fff
944 </style>