Fix Shogi.js
[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) {
28b32b4f 654 e.preventDefault();
1ef65040 655 if (!this.mobileBrowser && e.which != 3)
49dad261
BA
656 // Cancel current drawing and circles, if any
657 this.cancelResetArrows();
1ef65040 658 if (this.mobileBrowser || e.which == 1) {
49dad261
BA
659 // Mouse left button
660 if (!this.start) {
8764102a
BA
661 this.containerPos =
662 document.getElementById("boardContainer").getBoundingClientRect();
49dad261
BA
663 // NOTE: classList[0] is enough: 'piece' is the first assigned class
664 const withPiece = (e.target.classList[0] == "piece");
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
8764102a
BA
708 this.containerPos =
709 document.getElementById("gamePosition").getBoundingClientRect();
49dad261
BA
710 let elem = e.target;
711 // Next loop because of potential marks
712 while (elem.tagName == "IMG") elem = elem.parentNode;
107dc1bd 713 this.startArrow = getSquareFromId(elem.id);
49dad261
BA
714 }
715 },
716 mousemove: function(e) {
717 if (!this.selectedPiece && !this.startArrow) return;
107dc1bd
BA
718 // Cancel if off boardContainer
719 const [offsetX, offsetY] =
720 this.mobileBrowser
10addfff 721 ? [e.changedTouches[0].clientX, e.changedTouches[0].clientY]
107dc1bd
BA
722 : [e.clientX, e.clientY];
723 if (
724 offsetX < this.containerPos.left ||
725 offsetX > this.containerPos.right ||
726 offsetY < this.containerPos.top ||
727 offsetY > this.containerPos.bottom
728 ) {
8764102a
BA
729 if (!!this.selectedPiece) {
730 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
731 delete this.selectedPiece;
732 this.selectedPiece = null;
733 this.start = null;
85b6326c
BA
734 this.possibleMoves = []; //in case of
735 this.click = "";
8764102a
BA
736 let selected = document.querySelector(".ghost");
737 if (!!selected) selected.classList.remove("ghost");
738 }
739 else {
740 this.startArrow = null;
741 this.movingArrow = null;
742 const currentArrow = document.getElementById("currentArrow");
743 if (!!currentArrow)
744 currentArrow.parentNode.removeChild(currentArrow);
745 }
107dc1bd
BA
746 return;
747 }
49dad261
BA
748 e.preventDefault();
749 if (!!this.selectedPiece) {
750 // There is an active element: move it around
28b32b4f
BA
751 Object.assign(
752 this.selectedPiece.style,
753 {
49dad261
BA
754 left: offsetX - this.start.x + "px",
755 top: offsetY - this.start.y + "px"
28b32b4f
BA
756 }
757 );
28b32b4f 758 }
49dad261
BA
759 else {
760 let elem = e.target;
761 // Next loop because of potential marks
762 while (elem.tagName == "IMG") elem = elem.parentNode;
763 // To center the arrow in square:
107dc1bd
BA
764 const movingCoords = getSquareFromId(elem.id);
765 if (
766 movingCoords[0] != this.startArrow[0] ||
767 movingCoords[1] != this.startArrow[1]
768 ) {
769 this.movingArrow = movingCoords;
770 this.drawCurrentArrow();
28b32b4f 771 }
49dad261 772 }
cf2343ce
BA
773 },
774 mouseup: function(e) {
28b32b4f 775 e.preventDefault();
1ef65040 776 if (this.mobileBrowser || e.which == 1) {
49dad261
BA
777 if (!this.selectedPiece) return;
778 // Drag'n drop. Selected piece is no longer needed:
779 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
780 delete this.selectedPiece;
781 this.selectedPiece = null;
782 this.processMoveAttempt(e);
1ef65040 783 } else if (e.which == 3) {
8764102a 784 if (!this.startArrow) return;
1ef65040 785 // Mouse right button
107dc1bd 786 this.movingArrow = null;
49dad261
BA
787 this.processArrowAttempt(e);
788 }
28b32b4f 789 },
e90bafa8
BA
790 // Called by BaseGame after partially undoing multi-moves:
791 resetCurrentAttempt: function() {
792 this.possibleMoves = [];
793 this.start = null;
794 this.click = "";
795 this.selectedPiece = null;
796 },
28b32b4f
BA
797 processMoveAttempt: function(e) {
798 // Obtain the move from start and end squares
cafe0166
BA
799 const [offsetX, offsetY] =
800 this.mobileBrowser
10addfff 801 ? [e.changedTouches[0].clientX, e.changedTouches[0].clientY]
cafe0166 802 : [e.clientX, e.clientY];
cf2343ce 803 let landing = document.elementFromPoint(offsetX, offsetY);
cf2343ce 804 // Next condition: classList.contains(piece) fails because of marks
6808d7a1 805 while (landing.tagName == "IMG") landing = landing.parentNode;
28b32b4f
BA
806 if (this.start.id == landing.id) {
807 if (this.click == landing.id) {
808 // Second click on same square: cancel current move
809 this.possibleMoves = [];
810 this.start = null;
811 this.click = "";
812 } else this.click = landing.id;
cf2343ce 813 return;
28b32b4f
BA
814 }
815 this.start = null;
bd76b456 816 // OK: process move attempt, landing is a square node
cf2343ce
BA
817 let endSquare = getSquareFromId(landing.id);
818 let moves = this.findMatchingMoves(endSquare);
819 this.possibleMoves = [];
3a2a7b5f
BA
820 if (moves.length > 1) {
821 this.clickTime = Date.now();
822 this.choices = moves;
823 } else if (moves.length == 1) this.play(moves[0]);
28b32b4f 824 // else: forbidden move attempt
cf2343ce 825 },
49dad261
BA
826 processArrowAttempt: function(e) {
827 // Obtain the arrow from start and end squares
828 const [offsetX, offsetY] = [e.clientX, e.clientY];
829 let landing = document.elementFromPoint(offsetX, offsetY);
830 // Next condition: classList.contains(piece) fails because of marks
831 while (landing.tagName == "IMG") landing = landing.parentNode;
107dc1bd
BA
832 const landingCoords = getSquareFromId(landing.id);
833 if (
834 this.startArrow[0] == landingCoords[0] &&
835 this.startArrow[1] == landingCoords[1]
836 ) {
49dad261
BA
837 // Draw (or erase) a circle
838 this.$set(this.circles, landing.id, !this.circles[landing.id]);
107dc1bd 839 }
49dad261
BA
840 else {
841 // OK: add arrow, landing is a new square
107dc1bd
BA
842 const currentArrow = document.getElementById("currentArrow");
843 currentArrow.parentNode.removeChild(currentArrow);
844 this.addArrow({
845 start: this.startArrow,
846 end: landingCoords
49dad261
BA
847 });
848 }
849 this.startArrow = null;
850 },
cf2343ce
BA
851 findMatchingMoves: function(endSquare) {
852 // Run through moves list and return the matching set (if promotions...)
28b32b4f
BA
853 return (
854 this.possibleMoves.filter(m => {
855 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
856 })
857 );
cf2343ce
BA
858 },
859 play: function(move) {
6808d7a1
BA
860 this.$emit("play-move", move);
861 }
862 }
cf2343ce
BA
863};
864</script>
4473050c 865
107dc1bd
BA
866<style lang="sass">
867// SVG dynamically added, so not scoped
868#arrowCanvas
869 pointer-events: none
870 position: absolute
871 top: 0
872 left: 0
873 width: 100%
874 height: 100%
875
876.svg-arrow
877 opacity: 0.65
878 stroke: #5f0e78
879 fill: none
880 marker-end: url(#arrow)
881
882.svg-line
883 stroke: black
884
8efb985e
BA
885.svg-diag
886 stroke: grey
887
107dc1bd
BA
888.arrow-head
889 fill: #5f0e78
890</style>
891
41c80bb6 892<style lang="sass" scoped>
26d8a01a
BA
893@import "@/styles/_board_squares_img.sass";
894
ffeaef85
BA
895//.game.reserve-div
896 // TODO: would be cleaner to restrict width so that it doesn't overflow
897 // Commented out because pieces would disappear over the board otherwise:
898 //overflow: hidden
50aed5a1 899.reserve-count
ffeaef85
BA
900 width: 100%
901 text-align: center
902 display: inline-block
903 position: absolute
9d4a0218 904.reserve-row
50aed5a1
BA
905 margin-bottom: 15px
906
6ec2feb2
BA
907.full-width
908 width: 100%
41cb9b94 909
50aed5a1 910.game
28b32b4f 911 user-select: none
cf94b843
BA
912 width: 100%
913 margin: 0
50aed5a1
BA
914 .board
915 cursor: pointer
50aed5a1
BA
916
917#choices
28b32b4f 918 user-select: none
168a5e4c
BA
919 margin: 0
920 position: absolute
50aed5a1
BA
921 z-index: 300
922 overflow-y: inherit
923 background-color: rgba(0,0,0,0)
924 img
925 cursor: pointer
926 background-color: #e6ee9c
927 &:hover
928 background-color: skyblue
929 &.choice-piece
930 width: 100%
931 height: auto
932 display: block
933
50aed5a1 934img.ghost
ffeaef85 935 // NOTE: no need to set z-index here, since opacity is low
50aed5a1 936 position: absolute
28b32b4f 937 opacity: 0.5
50aed5a1
BA
938 top: 0
939
311cba76
BA
940.incheck-light
941 background-color: rgba(204, 51, 0, 0.7) !important
942.incheck-dark
943 background-color: rgba(204, 51, 0, 0.9) !important
50aed5a1 944
28b32b4f
BA
945// TODO: no predefined highlight colors, but layers. How?
946
90df90bc
BA
947.hover-highlight:hover
948 // TODO: color dependant on board theme, or inner border...
00eef1ca 949 background-color: #C571E6 !important
90df90bc 950
f63ba277
BA
951.highlight
952 &.light-square
953 &.lichess
954 background-color: #cdd26a
955 &.chesscom
956 background-color: #f7f783
957 &.chesstempo
958 background-color: #9f9fff
959 &.orangecc
960 background-color: #fef273
961 &.dark-square
962 &.lichess
963 background-color: #aaa23a
964 &.chesscom
965 background-color: #bacb44
966 &.chesstempo
967 background-color: #557fff
968 &.orangecc
969 background-color: #e8c525
970 &.middle-square
971 &.lichess
972 background-color: #BCBA52
973 &.chesscom
974 background-color: #D9E164
975 &.chesstempo
976 background-color: #7A8FFF
977 &.orangecc
978 background-color: #F3DC4C
4473050c 979</style>