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