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