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