Attempt to clarify installation instructions a little
[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,
bc1e1f2a 34 initialized: 0,
6808d7a1 35 settings: store.state.settings
cf2343ce
BA
36 };
37 },
38 render(h) {
6808d7a1 39 if (!this.vr) {
7b3cf1b7 40 // Return empty div of class 'game' to avoid error when setting size
107dc1bd
BA
41 return h(
42 "div",
43 { "class": { game: true } }
44 );
7b3cf1b7 45 }
6808d7a1 46 const [sizeX, sizeY] = [V.size.x, V.size.y];
cf2343ce 47 // Precompute hints squares to facilitate rendering
e2732923 48 let hintSquares = ArrayFun.init(sizeX, sizeY, false);
6808d7a1
BA
49 this.possibleMoves.forEach(m => {
50 hintSquares[m.end.x][m.end.y] = true;
51 });
cf2343ce 52 // Also precompute in-check squares
e2732923 53 let incheckSq = ArrayFun.init(sizeX, sizeY, false);
6808d7a1
BA
54 this.incheck.forEach(sq => {
55 incheckSq[sq[0]][sq[1]] = true;
56 });
06e79b07 57
af34341d
BA
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 => {
00eef1ca 64 if (!m.start.noHighlight && V.OnBoard(m.start.x, m.start.y))
b406466b 65 lmHighlights[m.start.x + sizeX * m.start.y] = true;
00eef1ca 66 if (!m.end.noHighlight && V.OnBoard(m.end.x, m.end.y))
b406466b 67 lmHighlights[m.end.x + sizeX * m.end.y] = true;
6e0f2842
BA
68 if (!!m.start.toplay)
69 // For Dice variant (at least?)
70 lmHighlights[m.start.toplay[0] + sizeX * m.start.toplay[1]] = true;
af34341d
BA
71 });
72 }
57eb158f
BA
73 const showLight = (
74 this.settings.highlight &&
4f524197 75 ["all", "highlight"].includes(V.ShowMoves)
57eb158f 76 );
d54f6261
BA
77 const showCheck = (
78 this.settings.highlight &&
4f524197 79 ["all", "highlight", "byrow"].includes(V.ShowMoves)
d54f6261 80 );
311cba76
BA
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) => {
af34341d 92 return showLight && !!lmHighlights[x + sizeX * y];
311cba76
BA
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)
9d4a0218 103 let elementArray = [];
cf2343ce 104 const gameDiv = h(
6808d7a1 105 "div",
cf2343ce 106 {
107dc1bd 107 attrs: { id: "gamePosition" },
6ec2feb2 108 "class": {
6808d7a1
BA
109 game: true,
110 clearer: true
111 }
cf2343ce
BA
112 },
113 [...Array(sizeX).keys()].map(i => {
311cba76 114 const ci = orientation == "w" ? i : sizeX - i - 1;
cf2343ce 115 return h(
6808d7a1 116 "div",
cf2343ce 117 {
6ec2feb2 118 "class": {
6808d7a1 119 row: true
cf2343ce 120 },
6808d7a1 121 style: { opacity: this.choices.length > 0 ? "0.5" : "1" }
cf2343ce
BA
122 },
123 [...Array(sizeY).keys()].map(j => {
311cba76 124 const cj = orientation == "w" ? j : sizeY - j - 1;
49dad261 125 const squareId = "sq-" + ci + "-" + cj;
cf2343ce 126 let elems = [];
311cba76 127 if (showPiece(ci, cj)) {
ffeaef85
BA
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));
cf2343ce 150 }
6808d7a1 151 if (this.settings.hints && hintSquares[ci][cj]) {
cf2343ce 152 elems.push(
6808d7a1 153 h("img", {
6ec2feb2 154 "class": {
6808d7a1
BA
155 "mark-square": true
156 },
157 attrs: {
158 src: "/images/mark.svg"
cf2343ce 159 }
6808d7a1 160 })
cf2343ce
BA
161 );
162 }
49dad261
BA
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 }
157a72c8
BA
175 const oddity = (ci + cj) % 2;
176 const lightSquare = (
177 (!V.DarkBottomRight && oddity == lightSquareMod) ||
178 (V.DarkBottomRight && oddity != lightSquareMod)
179 );
cf2343ce 180 return h(
6808d7a1 181 "div",
cf2343ce 182 {
6ec2feb2 183 "class": {
6808d7a1
BA
184 board: true,
185 ["board" + sizeY]: true,
ffeaef85
BA
186 "light-square":
187 !V.Notoodark && lightSquare && !V.Monochrome,
188 "dark-square":
189 !V.Notoodark && (!lightSquare || !!V.Monochrome),
190 "middle-square": V.Notoodark,
dfeb96ea 191 [this.settings.bcolor]: true,
311cba76 192 "in-shadow": inShadow(ci, cj),
f63ba277 193 "highlight": inHighlight(ci, cj),
2c5d7b20
BA
194 "incheck-light":
195 showCheck && lightSquare && incheckSq[ci][cj],
196 "incheck-dark":
90df90bc 197 showCheck && !lightSquare && incheckSq[ci][cj],
7c05a5f2
BA
198 "hover-highlight":
199 this.vr.hoverHighlight(
200 [ci, cj], !this.analyze ? this.userColor : null)
cf2343ce
BA
201 },
202 attrs: {
6808d7a1
BA
203 id: getSquareId({ x: ci, y: cj })
204 }
cf2343ce
BA
205 },
206 elems
207 );
208 })
209 );
24340cae 210 })
cf2343ce 211 );
9d4a0218
BA
212 if (!!this.vr.reserve) {
213 const playingColor = this.userColor || "w"; //default for an observer
6808d7a1 214 const shiftIdx = playingColor == "w" ? 0 : 1;
107dc1bd
BA
215 // Some variants have more than sizeY reserve pieces (Clorange: 10)
216 const reserveSquareNb = Math.max(sizeY, V.RESERVE_PIECES.length);
cf2343ce 217 let myReservePiecesArray = [];
1e8a8386
BA
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:
d5af4af2
BA
303 const nbReservePieces =
304 Math.max(myReservePiecesArray.length, oppReservePiecesArray.length);
1e8a8386
BA
305 const marginLeft =
306 ((100 - nbReservePieces * (100 / reserveSquareNb)) / 2) + "%";
307 if (hasReserveTop) {
308 var reserveTop =
6808d7a1
BA
309 h(
310 "div",
311 {
1e8a8386
BA
312 "class": {
313 game: true,
314 "reserve-div": true
315 },
316 style: {
317 "margin-left": marginLeft
318 }
6808d7a1
BA
319 },
320 [
ffeaef85 321 h(
1e8a8386 322 "div",
ffeaef85 323 {
1e8a8386
BA
324 "class": {
325 row: true,
326 "reserve-row": true
327 }
ffeaef85 328 },
1e8a8386 329 myReserveTop ? myReservePiecesArray : oppReservePiecesArray
ffeaef85 330 )
6808d7a1 331 ]
1e8a8386 332 );
cf2343ce 333 }
1e8a8386
BA
334 if (hasReserveBottom) {
335 var reserveBottom =
6808d7a1
BA
336 h(
337 "div",
338 {
1e8a8386
BA
339 "class": {
340 game: true,
341 "reserve-div": true
342 },
343 style: {
344 "margin-left": marginLeft
345 }
6808d7a1
BA
346 },
347 [
ffeaef85 348 h(
1e8a8386 349 "div",
ffeaef85 350 {
1e8a8386
BA
351 "class": {
352 row: true,
353 "reserve-row": true
354 }
ffeaef85 355 },
1e8a8386 356 myReserveTop ? oppReservePiecesArray : myReservePiecesArray
ffeaef85 357 )
6808d7a1 358 ]
1e8a8386 359 );
cf2343ce 360 }
1e8a8386 361 if (hasReserveTop) elementArray.push(reserveTop);
cf2343ce 362 }
9d4a0218 363 elementArray.push(gameDiv);
1e8a8386
BA
364 if (!!this.vr.reserve && hasReserveBottom)
365 elementArray.push(reserveBottom);
107dc1bd
BA
366 const boardElt = document.getElementById("gamePosition");
367 // boardElt might be undefine (at first drawing)
6808d7a1 368 if (this.choices.length > 0 && !!boardElt) {
107dc1bd 369 const squareWidth = boardElt.offsetWidth / sizeY;
aafe9f16 370 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
14edde72 371 const maxNbeltsPerRow = Math.min(this.choices.length, sizeY);
cdab5663 372 let topOffset = offset[0] + ((sizeX - 1) / 2) * squareWidth;
14edde72
BA
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 }
aafe9f16 379 const choices = h(
6808d7a1 380 "div",
aafe9f16 381 {
6808d7a1 382 attrs: { id: "choices" },
6ec2feb2 383 "class": { row: true },
aafe9f16 384 style: {
14edde72 385 top: topOffset + "px",
6808d7a1
BA
386 left:
387 offset[1] +
14edde72 388 (squareWidth * Math.max(sizeY - this.choices.length, 0)) / 2 +
6808d7a1 389 "px",
14edde72
BA
390 width: (maxNbeltsPerRow * squareWidth) + "px",
391 height: choicesHeight + "px"
6808d7a1 392 }
aafe9f16 393 },
14edde72
BA
394 [ h(
395 "div",
6ec2feb2
BA
396 {
397 "class": { "full-width": true }
398 },
14edde72
BA
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;
14edde72 406 this.choices = [];
78c23cd6 407 this.play(m);
14edde72 408 };
83cecc0f 409 const stopPropagation = (e) => { e.stopPropagation(); }
14edde72
BA
410 const onClick =
411 this.mobileBrowser
83cecc0f
BA
412 // Must cancel mousedown logic:
413 ? { touchstart: stopPropagation, touchend: applyMove }
414 : { mousedown: stopPropagation, mouseup: applyMove };
14edde72
BA
415 return h(
416 "div",
417 {
6ec2feb2 418 "class": {
14edde72
BA
419 board: true,
420 ["board" + sizeY]: true
aafe9f16 421 },
14edde72
BA
422 style: {
423 width: (100 / maxNbeltsPerRow) + "%",
424 "padding-bottom": (100 / maxNbeltsPerRow) + "%"
425 }
426 },
427 [
428 h("img", {
429 attrs: {
430 src:
431 "/images/pieces/" +
173f11dc 432 // orientation: extra arg useful for some variants
c7550017 433 this.vr.getPPpath(m, this.orientation) +
14edde72
BA
434 V.IMAGE_EXTENSION
435 },
6ec2feb2 436 "class": { "choice-piece": true },
14edde72
BA
437 on: onClick
438 })
439 ]
440 );
441 })
442 ) ]
aafe9f16
BA
443 );
444 elementArray.unshift(choices);
445 }
4b26ecb8
BA
446 let onEvents = {};
447 // NOTE: click = mousedown + mouseup
cafe0166 448 if (this.mobileBrowser) {
4b26ecb8
BA
449 onEvents = {
450 on: {
451 touchstart: this.mousedown,
452 touchmove: this.mousemove,
6808d7a1
BA
453 touchend: this.mouseup
454 }
4b26ecb8 455 };
1e8a8386
BA
456 }
457 else {
4b26ecb8 458 onEvents = {
cf2343ce 459 on: {
65495c17
BA
460 mousedown: this.mousedown,
461 mousemove: this.mousemove,
49dad261
BA
462 mouseup: this.mouseup,
463 contextmenu: this.blockContextMenu
6808d7a1 464 }
4b26ecb8
BA
465 };
466 }
bc1e1f2a
BA
467 if (this.initialized == 1) this.$emit("rendered");
468 if (this.initialized <= 1) this.initialized++;
107dc1bd
BA
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();
cf2343ce
BA
479 },
480 methods: {
49dad261
BA
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 = {};
107dc1bd
BA
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 };
49dad261 511 },
107dc1bd
BA
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]);
cd049aa1
BA
516 // Simple heuristic for now, just remove 1/3 square.
517 // TODO: should depend on the orientation.
cd049aa1
BA
518 const fracSqWidth = squareWidth / 3;
519 return {
107dc1bd
BA
520 x: endCoords.x - delta[0] * fracSqWidth / dist,
521 y: endCoords.y - delta[1] * fracSqWidth / dist
cd049aa1
BA
522 };
523 },
107dc1bd
BA
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) {
2c33215f
BA
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()
107dc1bd
BA
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() {
7c05a5f2
BA
589 // Add some drawing on board (for some variants + arrows and circles)
590 const boardElt = document.getElementById("gamePosition");
591 if (!boardElt) return;
107dc1bd
BA
592 // Remove current canvas, if any
593 const curCanvas = document.getElementById("arrowCanvas");
594 if (!!curCanvas) curCanvas.parentNode.removeChild(curCanvas);
107dc1bd
BA
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");
8efb985e
BA
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");
107dc1bd
BA
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 },
cf2343ce 653 mousedown: function(e) {
1ef65040 654 if (!this.mobileBrowser && e.which != 3)
49dad261
BA
655 // Cancel current drawing and circles, if any
656 this.cancelResetArrows();
1ef65040 657 if (this.mobileBrowser || e.which == 1) {
49dad261
BA
658 // Mouse left button
659 if (!this.start) {
8764102a
BA
660 this.containerPos =
661 document.getElementById("boardContainer").getBoundingClientRect();
49dad261
BA
662 // NOTE: classList[0] is enough: 'piece' is the first assigned class
663 const withPiece = (e.target.classList[0] == "piece");
cfc1cf0d 664 if (withPiece) e.preventDefault();
49dad261 665 // Show possible moves if current player allowed to play
9a7a1ccc
BA
666 const startSquare =
667 getSquareFromId(withPiece ? e.target.parentNode.id : e.target.id);
49dad261
BA
668 this.possibleMoves = [];
669 const color = this.analyze ? this.vr.turn : this.userColor;
9a7a1ccc
BA
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);
d2af3400
BA
674 const sq = getSquareFromId(targetId);
675 this.$emit("click-square", sq);
676 if (withPiece && !this.vr.onlyClick(sq)) {
9a7a1ccc 677 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
cbe95378
BA
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 }
49dad261 701 }
9a7a1ccc 702 }
49dad261 703 }
9a7a1ccc
BA
704 else this.processMoveAttempt(e);
705 }
706 else if (e.which == 3) {
1ef65040 707 // Mouse right button
cfc1cf0d 708 e.preventDefault();
8764102a
BA
709 this.containerPos =
710 document.getElementById("gamePosition").getBoundingClientRect();
49dad261
BA
711 let elem = e.target;
712 // Next loop because of potential marks
713 while (elem.tagName == "IMG") elem = elem.parentNode;
107dc1bd 714 this.startArrow = getSquareFromId(elem.id);
49dad261 715 }
cfc1cf0d 716 else e.preventDefault();
49dad261
BA
717 },
718 mousemove: function(e) {
719 if (!this.selectedPiece && !this.startArrow) return;
107dc1bd
BA
720 // Cancel if off boardContainer
721 const [offsetX, offsetY] =
722 this.mobileBrowser
10addfff 723 ? [e.changedTouches[0].clientX, e.changedTouches[0].clientY]
107dc1bd
BA
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 ) {
8764102a
BA
731 if (!!this.selectedPiece) {
732 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
733 delete this.selectedPiece;
734 this.selectedPiece = null;
735 this.start = null;
85b6326c
BA
736 this.possibleMoves = []; //in case of
737 this.click = "";
8764102a
BA
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 }
107dc1bd
BA
748 return;
749 }
49dad261
BA
750 e.preventDefault();
751 if (!!this.selectedPiece) {
752 // There is an active element: move it around
28b32b4f
BA
753 Object.assign(
754 this.selectedPiece.style,
755 {
49dad261
BA
756 left: offsetX - this.start.x + "px",
757 top: offsetY - this.start.y + "px"
28b32b4f
BA
758 }
759 );
28b32b4f 760 }
49dad261
BA
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:
107dc1bd
BA
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();
28b32b4f 773 }
49dad261 774 }
cf2343ce
BA
775 },
776 mouseup: function(e) {
1ef65040 777 if (this.mobileBrowser || e.which == 1) {
49dad261 778 if (!this.selectedPiece) return;
cfc1cf0d 779 e.preventDefault();
49dad261
BA
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);
cfc1cf0d
BA
785 }
786 else if (e.which == 3) {
787 e.preventDefault();
8764102a 788 if (!this.startArrow) return;
1ef65040 789 // Mouse right button
107dc1bd 790 this.movingArrow = null;
49dad261
BA
791 this.processArrowAttempt(e);
792 }
28b32b4f 793 },
e90bafa8
BA
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 },
28b32b4f
BA
801 processMoveAttempt: function(e) {
802 // Obtain the move from start and end squares
cafe0166
BA
803 const [offsetX, offsetY] =
804 this.mobileBrowser
10addfff 805 ? [e.changedTouches[0].clientX, e.changedTouches[0].clientY]
cafe0166 806 : [e.clientX, e.clientY];
cf2343ce 807 let landing = document.elementFromPoint(offsetX, offsetY);
cf2343ce 808 // Next condition: classList.contains(piece) fails because of marks
6808d7a1 809 while (landing.tagName == "IMG") landing = landing.parentNode;
28b32b4f
BA
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;
cf2343ce 817 return;
28b32b4f
BA
818 }
819 this.start = null;
bd76b456 820 // OK: process move attempt, landing is a square node
cf2343ce
BA
821 let endSquare = getSquareFromId(landing.id);
822 let moves = this.findMatchingMoves(endSquare);
823 this.possibleMoves = [];
3a2a7b5f
BA
824 if (moves.length > 1) {
825 this.clickTime = Date.now();
826 this.choices = moves;
827 } else if (moves.length == 1) this.play(moves[0]);
28b32b4f 828 // else: forbidden move attempt
cf2343ce 829 },
49dad261
BA
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;
107dc1bd
BA
836 const landingCoords = getSquareFromId(landing.id);
837 if (
838 this.startArrow[0] == landingCoords[0] &&
839 this.startArrow[1] == landingCoords[1]
840 ) {
49dad261
BA
841 // Draw (or erase) a circle
842 this.$set(this.circles, landing.id, !this.circles[landing.id]);
107dc1bd 843 }
49dad261
BA
844 else {
845 // OK: add arrow, landing is a new square
107dc1bd
BA
846 const currentArrow = document.getElementById("currentArrow");
847 currentArrow.parentNode.removeChild(currentArrow);
848 this.addArrow({
849 start: this.startArrow,
850 end: landingCoords
49dad261
BA
851 });
852 }
853 this.startArrow = null;
854 },
cf2343ce
BA
855 findMatchingMoves: function(endSquare) {
856 // Run through moves list and return the matching set (if promotions...)
28b32b4f
BA
857 return (
858 this.possibleMoves.filter(m => {
859 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
860 })
861 );
cf2343ce
BA
862 },
863 play: function(move) {
6808d7a1
BA
864 this.$emit("play-move", move);
865 }
866 }
cf2343ce
BA
867};
868</script>
4473050c 869
107dc1bd
BA
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
8efb985e
BA
889.svg-diag
890 stroke: grey
891
107dc1bd
BA
892.arrow-head
893 fill: #5f0e78
894</style>
895
41c80bb6 896<style lang="sass" scoped>
01ad8e17 897@import "@/styles/_board_squares_img.sass"
26d8a01a 898
ffeaef85
BA
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
50aed5a1 903.reserve-count
ffeaef85
BA
904 width: 100%
905 text-align: center
906 display: inline-block
907 position: absolute
9d4a0218 908.reserve-row
50aed5a1
BA
909 margin-bottom: 15px
910
6ec2feb2
BA
911.full-width
912 width: 100%
41cb9b94 913
50aed5a1 914.game
28b32b4f 915 user-select: none
cf94b843
BA
916 width: 100%
917 margin: 0
50aed5a1
BA
918 .board
919 cursor: pointer
50aed5a1
BA
920
921#choices
28b32b4f 922 user-select: none
168a5e4c
BA
923 margin: 0
924 position: absolute
50aed5a1
BA
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
50aed5a1 938img.ghost
ffeaef85 939 // NOTE: no need to set z-index here, since opacity is low
50aed5a1 940 position: absolute
28b32b4f 941 opacity: 0.5
50aed5a1
BA
942 top: 0
943
311cba76
BA
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
50aed5a1 948
28b32b4f
BA
949// TODO: no predefined highlight colors, but layers. How?
950
90df90bc
BA
951.hover-highlight:hover
952 // TODO: color dependant on board theme, or inner border...
00eef1ca 953 background-color: #C571E6 !important
90df90bc 954
f63ba277
BA
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
4473050c 983</style>