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