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