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