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